后台发送POST,DELETE,GET,PUT请求

public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, int> parameters, string userAgent, Encoding requestEncoding)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
if (requestEncoding == null)
{
throw new ArgumentNullException("requestEncoding");
}
HttpWebRequest request = null;
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "DELETE";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("ContentType", "text/xml; charset=utf-8");
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
//else
//{
// request.UserAgent = DefaultUserAgent;
//}
//如果需要POST数据
if (!(parameters == null || parameters.Count == 0))
{
var 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);
}
}
return request.GetResponse() as HttpWebResponse;
}

posted @ 2013-12-16 14:21  忆如梨花  阅读(684)  评论(0编辑  收藏  举报