HttpWebRequest使用总结
Posted xiaohua19920
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpWebRequest使用总结相关的知识,希望对你有一定的参考价值。
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使用总结的主要内容,如果未能解决你的问题,请参考以下文章
HttpWebRequest的GetResponse或GetRequestStream偶尔超时 + 总结各种超时死掉的可能和相应的解决办法
转载HttpWebRequest的GetResponse或GetRequestStream偶尔超时 + 总结各种超时死掉的可能和相应的解决办法