Home >Backend Development >C++ >How to Make HTTPS Calls with HttpClient Using TLS 1.2?

How to Make HTTPS Calls with HttpClient Using TLS 1.2?

DDD
DDDOriginal
2025-01-17 23:51:09614browse

How to Make HTTPS Calls with HttpClient Using TLS 1.2?

Securing HTTPS Communication with HttpClient

The HttpClient class simplifies HTTP requests, but HTTPS connections can sometimes present difficulties, particularly when servers only support newer TLS versions like TLS 1.2. This article addresses this common problem.

To ensure compatibility with TLS 1.2 (and other relevant versions), add this line of code:

<code class="language-csharp">System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;</code>

This command explicitly enables TLS 1.2, TLS 1.1, and TLS 1.0, providing broader compatibility with various servers.

Here's how to integrate this into your HttpClient code:

<code class="language-csharp">HttpClient httpClient = new HttpClient();

// Enable TLS 1.2 and other compatible protocols
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);</code>

By incorporating this adjustment, your application will reliably connect to HTTPS servers using secure TLS protocols, allowing for successful data exchange.

The above is the detailed content of How to Make HTTPS Calls with HttpClient Using TLS 1.2?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn