HttpWebRequest的KeepAlive默认是true,如果使用的时候仅仅只是关闭流,不关闭网卡上的通道的话,第二个请求在TCP没有关闭的情况下是走同一个通道,此时本机的TCP通道就会抛异常出来,这是本机抛的错误。所以除了关闭本机的IO资源外,还要关闭网络资源。需要把KeepAlive设置成false就可以了。TCP通信结束后会自动关闭该请求所使用的通道。
request.About() 是发现异常就断掉
http是上层协议,底层还是走tcp的,如果不关闭的话,第二个http会默认走没有关闭的tcp。如果有并发的时候,数据就乱了。所以应该及时关闭tcp,每次开一个新端口。
public string PostToHttpService(string url, string jsonData, string userName, string password)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.Credentials = new NetworkCredential(userName, password);
request.Timeout = 180000;//两分钟
request.ReadWriteTimeout = 180000;//两分钟
request.KeepAlive = false;
byte[] datas = Encoding.UTF8.GetBytes(jsonData);
request.ContentLength = datas.Length;
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(datas, 0, datas.Length);
requestStream.Close();
}
catch (System.Net.ProtocolViolationException ex)
{
request.Abort();
}
catch (System.Net.WebException ex)
{
request.Abort();
}
catch (System.ObjectDisposedException ex)
{
request.Abort();
}
catch (System.InvalidOperationException ex)
{
request.Abort();
}
catch (System.NotSupportedException ex)
{
request.Abort();
}
HttpWebResponse response = null;
string responseDatas = string.Empty;
try
{
response = (HttpWebResponse)request.GetResponse();
Stream streamResponse = response.GetResponseStream();
using (StreamReader sr = new StreamReader(streamResponse))
{
responseDatas = sr.ReadToEnd();
}
}
catch (Exception ex)
{
request.Abort();
}
finally
{
if (response != null)
{
try
{
response.Close();
}
catch {
request.Abort();
}
}
}
return responseDatas;
}