Home > Backend Development > C++ > How Can I Fix 'Could Not Establish Trust Relationship' Errors When Making HTTPS Calls with HttpClient?

How Can I Fix 'Could Not Establish Trust Relationship' Errors When Making HTTPS Calls with HttpClient?

Susan Sarandon
Release: 2025-01-18 00:24:13
Original
798 people have browsed it

How Can I Fix

Use HttpClient to make secure HTTPS calls

Question:

When using HttpClient to make an HTTPS request, an error occurs: "The underlying connection was closed: Unable to establish trust for the SSL/TLS secure channel."

Solution:

To resolve this issue, please follow these steps:

  1. Set security protocol:

    Specify the TLS protocol used by default. Add the following lines to your code:

    <code class="language-csharp">System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;</code>
    Copy after login
  2. Modify HttpClient code:

    Modified HttpClient code to support HTTPS calls:

    <code class="language-csharp">HttpClient httpClient = new HttpClient();
    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>
    Copy after login

Additional notes:

  • This solution assumes that the server only supports higher TLS versions (for example, TLS 1.2).
  • If the server requires a custom certificate or key, additional configuration is required.

The above is the detailed content of How Can I Fix 'Could Not Establish Trust Relationship' Errors When Making HTTPS Calls with HttpClient?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template