我有这段代码可创建请求并读取数据,但始终为空
static string uri = "http://yiimp.ccminer.org/api/wallet?address=DshDF3zmCX9PUhafTAzxyQidwgdfLYJkBrd";
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
Console.WriteLine("Response stream received.");
Console.WriteLine(readStream.ReadToEnd());
response.Close();
readStream.Close();
}
当我尝试从浏览器访问链接时,得到此json:
{"currency": "DCR", "unsold": 0.030825917365192, "balance": 0.02007306, "unpaid": 0.05089898, "paid24h": 0.05796425, "total": 0.10886323}
我想念什么?
最佳答案
当您从浏览器执行请求时,有许多 header 发送到Web服务。显然,此Web服务验证UserAgent。这是Web服务实现方面的决定,他们可能不希望您以编程方式访问它。
var client = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://yiimp.ccminer.org/api/wallet?address=DshDF3zmCX9PUhafTAzxyQidwgdfLYJkBrd"));
client.AutomaticDecompression = DecompressionMethods.GZip;
client.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063";
client.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
client.Host = "yiimp.ccminer.org";
client.KeepAlive = true;
using (var s = client.GetResponse().GetResponseStream())
using (var sw = new StreamReader(s))
{
var ss = sw.ReadToEnd();
Console.WriteLine(ss);
}
发送 header 似乎可以使其正常工作。
关于c# - 从url读取数据返回空值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45977298/