C#使用 WebRequest 异步获取网页并自动忽略SSL证书
2022/2/18 20:41:40
本文主要是介绍C#使用 WebRequest 异步获取网页并自动忽略SSL证书,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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
这篇关于C#使用 WebRequest 异步获取网页并自动忽略SSL证书的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-12-06使用Microsoft.Extensions.AI在.NET中生成嵌入向量
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#