C#使用 WebRequest 模拟浏览器请求访问网页并自动忽略HTTPS安全证书
以下两个C#异步方法,封装了WebRequest请求,支持忽略SSL证书。
作者:张赐荣
1.Get请求
public static Task<string> HTTP_Get(string URL, string[] headers = null) // HTTP Get 请求
{
Task<string> ts = Task.Run(() => {
System.Net.HttpWebRequest hwr = System.Net.HttpWebRequest.Create(URL) as System.Net.HttpWebRequest;
hwr.Proxy = null;
hwr.Method = "GET";
hwr.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64; Trident/7.0; MSIE/11.0; rv:11.0;) like Gecko";
hwr.Referer = URL;
hwr.ServerCertificateValidationCallback = (_s, _x509s, _x509c, _ssl) => { return (true); };
try
{
if (headers != null)
{
foreach (var item in headers)
{
hwr.Headers.Add(item);
}
}
using (System.IO.StreamReader sr = new System.IO.StreamReader(hwr.GetResponseAsync().Result.GetResponseStream()))
{
return (sr.ReadToEnd());
}
}
catch (Exception ex)
{
Program.Log(ex.ToString());
return ("");
}
});
return (ts);
}
2.Post 请求:
public static Task<string> HTTP_Post(string URL, string Data, string[] headers = null) // HTTP Post 请求
{
Task<string> ts = Task.Run(() => {
System.Net.HttpWebRequest hwr = System.Net.HttpWebRequest.Create(URL) as System.Net.HttpWebRequest;
hwr.Method = "POST";
hwr.Proxy = null;
hwr.ContentType = "application/x-www-form-urlencoded";
hwr.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64; Trident/7.0; MSIE/11.0; rv:11.0;) like Gecko";
hwr.ServerCertificateValidationCallback = (_s, _x509s, _x509c, _ssl) => { return (true); };
try
{
if (headers != null)
{
foreach (var item in headers)
{
hwr.Headers.Add(item);
}
}
byte[] tmp = Encoding.GetEncoding("UTF-8").GetBytes(Data);
hwr.GetRequestStream().WriteAsync(tmp, 0, tmp.Length);
using (System.IO.StreamReader sr = new System.IO.StreamReader(hwr.GetResponseAsync().Result.GetResponseStream()))
{
return (sr.ReadToEnd());
}
}
catch (Exception ex)
{
Program.Log(ex.ToString());
return ("");
}
});
return (ts);
}
参考:
WebRequest 文档:
https://docs.microsoft.com/zh-cn/dotnet/api/system.net.webrequest?redirectedfrom=MSDN&view=net-6.0