private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
///
/// 创建POST方式的HTTP请求
///
/// 请求的URL
/// 随同请求POST的参数名称及参数值字典
/// 请求的超时时间
/// 请求的客户端浏览器信息,可以为空
/// 发送HTTP请求时所用的编码
/// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空
///
public static string PostHttpResponse(string url, Dictionaryparameters,
int? timeout)
{
try
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ServicePoint.Expect100Continue = false;
request.ServicePoint.UseNagleAlgorithm = false; //是否使用 Nagle 不使用 提高效率
//request.AllowWriteStreamBuffering = false; //数据是否缓冲 false 提高效率
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = DefaultUserAgent;
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
else
{
request.Timeout = 20000;
}
Encoding requestEncoding = Encoding.GetEncoding("UTF-8");
//如果需要POST数据
if (!(parameters == null || parameters.Count == 0))
{
StringBuilder buffer = new StringBuilder();
int i = 0;
foreach (string key in parameters.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, parameters[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, parameters[key]);
}
i++;
}
byte[] data = requestEncoding.GetBytes(buffer.ToString());
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
//获取响应,并设置响应编码
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
//读取响应流
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string returnData = reader.ReadToEnd();
reader.Dispose();
response.Close();
return returnData;
}
catch (Exception ex)
{
MessageUtil.ShowWarning(ex.Message);
}
return "";
}
请求接口的方法
Dictionaryparameters = new Dictionary ();
parameters.Add("USER_ACCOUNT", UserName);
parameters.Add("USER_PASSWORD", pwd);
return HttpPostHelper.PostHttpResponse("接口URL", parameters, null);