本人在改造旧项目时遇到一个http发送请求在本地怎么都好使,但是在测试服务器始终失败的问题,给的错误信息也只有一句话:“发送请求时出错”,使用的是HttpClient对象发出的请求。
使用PostMan也是可以正常发送的,但是就是一到测试服务器就失败,我的测试服务器是配置了https证书的,目标服务器也是https,费了好久排查代码问题,甚至不惜更换底层代码还是不好使。 被逼无奈还是百度吧,没想到网上早就有类似问题了:
我的上一篇采坑文章:APP项目http请求无法通信的错误:c# – 因为算法不同,客户端和服务器无法通信
原因是:发送请求的消息http协议版本问题,应该设置.net 4.5支持的最高版本TLZ1.2,我原来已经遇到过一次这个坑了,只是上次的坑错误比较明显,这次的坑就这么一句不明不白的话。 哎,“发送请求时出错”。
解决方案:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
道友地址:c# WebClient,HttpClient 发送请求出错时解决办法
在C# 使用 HttpClient或 WebClient发送请求时
提示 :
请求被中止: 未能创建 SSL/TLS 安全通道
或
发送请求时出错
的问题
解决办法:在发送请求地址代码前加如下代码
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;( | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;)
问题解决!
如:
HttpClient httpClient = new HttpClient();
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var res = await httpClient.GetAsync(url);
var contentStr = await res.Content.ReadAsStringAsync();
或者(经过测试,下面的方法是不好使的,大家看到时使用第一种方案):
handler = new HttpClientHandler() ;
handler.AllowAutoRedirect = true;
handler.UseCookies = true;
handler.CookieContainer = cookies;
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
httpClient = new HttpClient(handler);