在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
问题 使用 HTTP Client 请求 HTTPS 的 API 时出现 下面就是问题代码: public class Program { public static void Main(string[] args) { var url = @"https://xxx.xxx.xxx.xxx:xxxx/xxx-web/services/xxxx?wsdl"; var handler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Manual, ClientCertificates = { new X509Certificate2(@"E:\cert\rootTrust.cer","11111111"), new X509Certificate2(@"E:\cert\middleTrust.cer","11111111"), new X509Certificate2(@"E:\cert\wskey.pfx","ws654321") } }; var webRequest = new HttpClient(handler); var result = webRequest.GetStringAsync(url).GetAwaiter().GetResult(); Console.WriteLine(result); } } 原因 因为在发出 HTTPS 请求的时候,HttpClient 都会检查 SSL 证书是否合法。如果不合法的话,就会导致抛出异常信息,而对方给出的证书是自签发的测试接口的证书,所以不是一个合法的 SSL 证书。 解决 在 最新的代码如下: public class Program { public static void Main(string[] args) { var url = @"https://xxx.xxx.xxx.xxx:xxxx/xxx-web/services/xxxx?wsdl"; var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true, ClientCertificateOptions = ClientCertificateOption.Manual, ClientCertificates = { new X509Certificate2(@"E:\cert\rootTrust.cer","11111111"), new X509Certificate2(@"E:\cert\middleTrust.cer","11111111"), new X509Certificate2(@"E:\cert\wskey.pfx","ws654321") } }; var webRequest = new HttpClient(handler); var result = webRequest.GetStringAsync(url).GetAwaiter().GetResult(); Console.WriteLine("xx"); } } 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持极客世界。 |
请发表评论