c# - 从 url 读取数据返回空值

标签 c# httpwebrequest

我有这段代码可以创建一个请求并读取数据,但它总是空的

        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 服务验证了 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/

相关文章:

c# - 如何将链接参数添加到 ASP.NET Core MVC 中的 asp 标记助手

c# - 如何在 wpf 中将两个组合框绑定(bind)在一起

c# - Entity Framework 建议无效的字段名称

c# - Xamarin 上的 WebHeaderCollection 和 HttpWebRequest

http - 在 Firefox 中使用篡改数据篡改 GET 请求参数?

c# - WebRequest 与代理到 whatsmyip.net 显示我的真实 ip

javascript - JQuery 中的 HTTP Get 请求到 Last.fm

c# - 根据执行 HttpWebRequest 的位置获得不同的响应

c# - 使用本地线程的单元测试方法

javascript - 来自 ajax 的模型绑定(bind),用于将日期值传递为 null