Adam Jachocki
Adam Jachocki

Reputation: 2125

HttpWebRequest - getting "Underlying connection was closed" error

I fight with this problem for 2 days and I'm really fed up. Nothing I find works.

Check this simple, example code:

HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(updateInfoFileUrl);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //768 for TLS 1.1 and 3072 for TLS 1.2
ServicePointManager.ServerCertificateValidationCallback = delegate
{
    return true;
};
fileReq.KeepAlive = false;

WebProxy proxy = new WebProxy();
proxy.BypassProxyOnLocal = false;
proxy.UseDefaultCredentials = true;
proxy.Credentials = CredentialCache.DefaultCredentials;
fileReq.Proxy = proxy;

HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
Stream stream = fileResp.GetResponseStream();

I tried different combinations of SecurityProtocols. Using only one, using all of them... Nothing works. I tried HttpWebRequest, HttpClient and even XmlDocument.Load. Nothing works. I got the error every time.

What can be wrong with it?

This is my document I want to read: https://www.example.com/info.xml

Browsers show it. Even PostMan shows it.

Upvotes: 1

Views: 189

Answers (1)

Vytautas Plečkaitis
Vytautas Plečkaitis

Reputation: 861

Did some debugging. It was not an issue with your code, but the server required user agent setting. Works :

HttpWebRequest fileReq = (HttpWebRequest)WebRequest.Create(@"https://www.example.com/info.xml");
fileReq.UserAgent = "sadsad";
fileReq.Method = "GET";

HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
Stream stream = fileResp.GetResponseStream();

Fails:

HttpWebRequest fileReq = (HttpWebRequest)WebRequest.Create(@"https://www.example.com/info.xml");

//     fileReq.UserAgent = "sadsad";
fileReq.Method = "GET";

HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
Stream stream = fileResp.GetResponseStream();

Upvotes: 3

Related Questions