IOException:无法从传输连接读取数据:连接已关闭

时间:2017-12-19 13:13:43

标签: c# httpwebrequest

尝试使用http:

发布网络服务时出现此错误
  

无法从传输连接读取数据:连接是   关闭

一些类似的问题:1

我的代码:

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

1 个答案:

答案 0 :(得分:0)

解决:

我评论了以下行代码:

//requestStream.Close();

KeepAlive使http连接成为持久连接, 它只在连接结束时关闭,Close()使它抛出异常。

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