Search code examples
c#apihttphttpsget

Error in sending HTTPS get request C#


I have this code to send Http Get Request to https URL but I am getting this error:

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

var webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Timeout = timeout;//timeout 100 sec by default

            using (var httpWebResponse = (HttpWebResponse)webRequest.GetResponse())
            using (var stream = httpWebResponse.GetResponseStream())
            using (var streamReader = new StreamReader(stream))
            {
                var response = streamReader.ReadToEnd();
                return response;
            }

The URL is working fine from browser and postman.


Solution

  • Try to add this code just above your WebRequest.Create(url);

    If you are using .Net Framework 4.0

    System.Net.ServicePointManager.SecurityProtocol =SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
    

    If you are using .Net Framework 4.5 and above

    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;