我一直在HttpClient使用C#进行WebApi调用。与相比似乎整洁快捷的方式WebClient。但是我在Https打电话时被困住了。
HttpClient
WebClient
Https
如何进行以下代码进行Https调用?
HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri("https://foobar.com/"); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/xml")); var task = httpClient.PostAsXmlAsync<DeviceRequest>( "api/SaveData", request);
编辑1: 上面的代码可以很好地进行http调用。但是,当我将方案更改为https时,它不起作用。这是获得的错误:
基础连接已关闭:无法为SSL / TLS安全通道建立信任关系。
编辑2: 将方案更改为https是:第一步。
我如何提供证书和公共/私人密钥以及C#请求。
如果服务器仅支持更高的TLS版本(例如仅TLS 1.2),则除非您的客户端PC默认配置为使用更高的TLS版本,否则服务器仍将失败。要解决此问题,请在代码中添加以下内容。
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
修改您的示例代码,它将是
HttpClient httpClient = new HttpClient(); //specify to use TLS 1.2 as default connection System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; httpClient.BaseAddress = new Uri("https://foobar.com/"); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); var task = httpClient.PostAsXmlAsync<DeviceRequest>("api/SaveData", request);