1

So I'm attempting to use the WebClient#downloadString(url) and it's not seeming to work, this is the error message:

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.

I'm not sure why this happens or how to fix it, if anyone could help me out with that than that would be great. My current code is this:

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

This code is mainly just for testing and it's not working at all. Anyone have any ideas? I've looked around a bit and can't find any way to fix this error.

C. Donavon
  • 56
  • 1
  • 8
  • 1
    Server has closed the connection, and not WebClient problem –  Aug 07 '16 at 04:15
  • Is there a specific reason the the server would close the connection? Is there a way I could keep the server open? – C. Donavon Aug 07 '16 at 04:35
  • 1
    Sometimes you need to set the user-agent header. Some servers are rejecting if user-agent is empty, like your WebClient : http://stackoverflow.com/questions/11841540/setting-the-user-agent-header-for-a-webclient-request –  Aug 07 '16 at 04:39
  • Worked like a charm, thank you very much @x... – C. Donavon Aug 07 '16 at 04:43
  • Jumping in late, but the National Weather Service did that same "block" about a year ago. Took me a bit to realize that's what they were looking for the user-agent header. – Wesley Long Aug 07 '16 at 05:10

1 Answers1

3

You must set the user-agent header. Some servers are rejecting connection if user-agent is empty:

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