c#webclient下载字符串错误

本文关键字:错误 字符串 下载 c#webclient | 更新日期: 2023-09-27 18:01:06

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

此代码主要用于测试,根本不起作用。有人有什么想法吗?我环顾四周,找不到任何方法来纠正这个错误。

c#webclient下载字符串错误

您必须设置用户代理标头。如果用户代理为空,某些服务器将拒绝连接:

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);
}