HttpWebRequest的KeepAlive默认是true
HttpWebRequest的KeepAlive默认是true,如果使用的时候仅仅只是封锁流,看qq空间访问权限破解 ,不封锁网卡上的通道的话,第二个请求在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;
}
HttpWebRequest使用总结
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/29312.html
- 上一篇:具有出色的社区
- 下一篇:开始轰轰烈烈的转型Java了