c#webclient downloadstring错误

时间:2016-08-07 04:11:26

标签: c# webclient

所以我试图使用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");

此代码主要用于测试,但根本不起作用。有人有主意吗?我已经环顾四周,无法找到解决此错误的方法。

1 个答案:

答案 0 :(得分:1)

您必须设置用户代理标头。如果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);
}
相关问题