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