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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM