c# webclient downloadstring 错误

c# webclient downloadstring error

所以我正在尝试使用 WebClient#downloadString(url) 但它似乎不起作用,这是错误消息:

An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user code 
Additional information: The underlying connection was closed: The connection was closed unexpectedly.

我不确定为什么会发生这种情况或如何解决它,如果有人能帮助我解决这个问题那就太好了。我当前的代码是这样的:

 string webData = new System.Net.WebClient().DownloadString("http://api.predator.wtf/host2ip/?arguments=www.google.com");

此代码主要用于测试,根本不起作用。谁有想法?我环顾四周,找不到解决此错误的任何方法。

您必须设置 user-agent header。如果 user-agent 为空,某些服务器将拒绝连接:

using (var w = new WebClient())
{
    w.Headers.Add("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36");
    var s = w.DownloadString("http://api.predator.wtf/host2ip/?arguments=www.google.com");
    Console.WriteLine(s);
}