HttpWebRequest使用总结
来源:互联网 发布:淘宝企业店铺资质要求 编辑:程序博客网 时间:2024/04/29 00:48
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;
}
0 0
- HttpWebRequest使用总结
- HttpWebRequest使用总结
- HttpWebRequest使用
- 使用HttpWebRequest提交信息
- HttpWebRequest使用问题
- C# 使用HttpWebRequest Post
- HttpWebRequest使用的注意事项
- HttpWebRequest简单使用
- HttpWebRequest
- HttpWebRequest
- HttpWebRequest
- HttpWebRequest
- HttpWebRequest
- HttpWebRequest
- HttpWebRequest
- httpwebrequest
- HttpWebRequest
- 使用HttpWebRequest自动更新客户端应用程序
- 倾听我黑色的大衣像我的你
- python编码
- 如何让view只响应一个按钮
- Openstack 二次开发之:在windows 环境下编译Openstack-java-sdk
- DataTemplate-根据条件选择不同模板
- HttpWebRequest使用总结
- [转]优酷土豆2012.9.12校园招聘会笔试题
- C# winform treeview node添加右键菜单并选中节点
- 如何制作C#安装程序
- stm32 can管脚重映谢
- 何必想何必问何处是我家
- 多少年快乐和忧伤
- static的作用
- python--urllib模块中的方法