C# HttpWebRequest请求服务器(Get/Post兼容)

简单示例说明

public static string HttpGet(string url, string data,string Method, int timeOut, Encoding encode, string contentType = "application/x-www-form-urlencoded", CookieContainer cookieContainer = null, string UserAgent = null)
{
string result = "";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
try
{
webRequest.Method = Method;//请求方式Get/Post
webRequest.Timeout = timeOut;//超时时间(毫秒单位)
webRequest.ContentType = contentType;//请求参数格式
webRequest.Accept = "*/*";//http标头多个以;隔开例:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
webRequest.UserAgent = UserAgent;//可为空
webRequest.Headers.Add("Name", "admin");//添加http标头可多个
webRequest.Headers.Add("Type", "1");//添加http标头可多个
if (!string.IsNullOrEmpty(data))
{
byte[] buffer = encode.GetBytes(data); // 转化 encode编码格式例:Encoding.UTF8
webRequest.ContentLength = buffer.Length;
//写入提交数据
using (System.IO.Stream newStream = webRequest.GetRequestStream())
{
newStream.Write(buffer, 0, buffer.Length); //写入参数
newStream.Flush();
}
}
//提交请求
using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)webRequest.GetResponse())
{
if (cookieContainer != null)
{
response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
}
//判断是否返回的是压缩信息
if (response.ContentEncoding.ToLower().Contains("gzip"))
{
using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader sreader = new StreamReader(stream))
{
result = sreader.ReadToEnd();
}
}
}
else
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, encode))
{
result = reader.ReadToEnd();
}
}
}
}
}
catch (WebException ex)
{
LogHelper.WriteErrorLog("时间:" + DateTime.Now + "--路径" + url + "--错误:" + ex);//错误写入日志
var httpErrResponse = ((HttpWebResponse)ex.Response);
using (var stream = httpErrResponse.GetResponseStream())
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
}
}
}
return result;
}

原文地址:https://www.cnblogs.com/ZxtIsCnblogs/p/12143744.html