【问题标题】:c# webclient downloadstring errorc# webclient下载字符串错误
【发布时间】:2016-08-07 04:11:25
【问题描述】:

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

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

【问题讨论】:

  • 服务器已经关闭连接,不是WebClient问题
  • 服务器关闭连接是否有特定原因?有没有办法让服务器保持打开状态?
  • 有时需要设置用户代理头。如果用户代理为空,则某些服务器会拒绝,例如您的 WebClient :stackoverflow.com/questions/11841540/…
  • 工作就像一个魅力,非常感谢@x...
  • 迟到了,但国家气象局大约一年前做了同样的“阻止”。我花了一点时间才意识到这就是他们正在寻找的用户代理标头。

标签: c# webclient


【解决方案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);
}

【讨论】:

  • 我只是将“答案”从“cmets”移动到“答案”...:=)
猜你喜欢
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多