Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host in C#
Asked Answered
F

3

7

I have a code where I am sending the URL request and receiving the response and storing it as a String as

public String GenerateXML(String q)// Here 'q' is the URL 
{
    // Generating the XML file for reference
    // Getting the response in XML format from the URL

    Debug.WriteLine("The Http URL after URL encoding :" + q);
    try
    {
        Uri signs1 = new Uri(q);
        //Debug.WriteLine("The Requested URL for getting the XML data :" + re);

        WebRequest request1 = WebRequest.Create(signs1);

        HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse();

        //HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse();

        Stream receiveStream = response1.GetResponseStream();

        StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

        String ab = readStream.ReadToEnd();// The mentioned error is showing up here.
        // Debug.WriteLine("The data :"+a);
        //XmlDocument content2 = new XmlDocument();

        // content2.LoadXml(ab);

        //  content2.Save("C:/Users/Administrator/Downloads/direct.xml");
        return ab;
    }
    catch (System.Net.WebException ex)
    {
        Debug.WriteLine("Exception caught :" + ex);
        return null;
    } 
}

Why is the connection closed by the remote host? What are the possibilities of getting rid of the error or at least ignore the error and continue with other URL requests? I have included try and catch so as to escape any error and continue functioning with out any stop. Scoured the internet for solution but solutions to this particular problem is pretty much specific. Please any help is appreciated. Thanks in advance.

Foscalina answered 30/1, 2014 at 2:1 Comment(3)
Maybe the server expects a different url, maybe it requires some special header in request, maybe it requires authentication etc......Swerve
@Swerve How to ignore this problem and continue progress with other URLs? I have already put in try and catch.What else should be done?Foscalina
Try/catch would not help here much. Find docs or if you have a working code use Fiddler to see what it sends and receives.Swerve
T
5

The actual exception is probably an IOException - you would need to catch that exception type as well as WebException. The actual problem may be that your URL is out of date and the system is no longer running a web server, or perhaps, the request needs to be authenticated/needs a header as @L.B suggests.

Also, you are potentially leaking all sorts of resources. You should be wrapping your WebResponse and streams in using statements.

using (var response = (HttpWebResponse)request.GetResponse())
using (var receiveStream = response.GetResponseStream())
using (var reader = new StreamReader(receiveStream))
{
     var content = reader.ReadToEnd();
     // parse your content, etc.
}
Tangerine answered 30/1, 2014 at 3:6 Comment(1)
Hey i came across the same issue my code is Dim payResp As HttpWebResponse = DirectCast(payReq.GetResponse(), HttpWebResponse) Dim sr As New StreamReader(payResp.GetResponseStream()) Dim response As String = sr.ReadToEnd() sr.Close()Egocentrism
H
5

I had similar problems with the connection being forcibly closed with different hosts. Seems the issue can be resolved by altering various properties of the WebRequest object.

The following findings were outlined in a blog post by briancaos: An existing connection was forcibly closed by the remote host

The steps mentioned in the the above post include:

Set WebRequest.KeepAlive to False.

Set WebRequest.ProtocolVersion to HttpVersion.Version10.

Set WebRequest.ServicePoint.ConnectionLimit to 1

It indeed work for me, but I haven't tested it on multiple hosts as of yet. However, I seriously suggest reading the post as it goes into way more detail.

In case the link get's broken, here's the Archive.org cached version.

Habiliment answered 14/3, 2015 at 12:4 Comment(0)
U
4

Had the same problem today, So I also wrapped the request in a try/catch with WebException, in my case, adding:

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Before the webRequest did the trick. Also you should be wrapping your WebResponse and streams in using statements as tvanfosson mentioned.

I hope this helps.

Unquote answered 9/1, 2019 at 3:21 Comment(1)
here's what TLS versions different .NET versions support: https://mcmap.net/q/523102/-system-net-securityprotocoltype-tls12-definition-not-foundMewl

© 2022 - 2024 — McMap. All rights reserved.