Search code examples
c#httpwebrequest

IOException: Unable to read data from the transport connection: The connection was closed


I'm getting this error while trying to posting web service with http:

Unable to read data from the transport connection: The connection was closed

some similar question: 1

My code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.KeepAlive = true;
request.ProtocolVersion = HttpVersion.Version10;
request.ServicePoint.ConnectionLimit = 24;

string dataText = items.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(dataText);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(byteArray, 0, byteArray.Length);
    requestStream.Close();
}

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseFromServer;
using (var reader = new StreamReader(response.GetResponseStream()))
{
    responseFromServer = reader.ReadToEnd();
    response.Close();
}

Solution

  • SOLVED:

    I've commented the line code of:

    //requestStream.Close();
    

    the KeepAlivemake the the http connection to be persistent connection, it only closing at the end of the connection, the Close() make it throw exception.

    https://en.wikipedia.org/wiki/HTTP_persistent_connection