Tuesday, April 18, 2023

How do you use HttpClient in .NET Core to make HTTP requests to external APIs?

In .NET Core, you can use the HttpClient class to make HTTP requests to external APIs. Here are the basic steps to use HttpClient:

1. Create an instance of the HttpClient class:

HttpClient client = new HttpClient();

2. Create a HttpRequestMessage object to specify the HTTP method, URL, headers, and body (if applicable):

HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Get;
request.RequestUri = new Uri("https://example.com/api/data");
request.Headers.Add("Authorization", "Bearer {access_token}");


3. Send the HTTP request using the SendAsync method of the HttpClient object:

HttpResponseMessage response = await client.SendAsync(request);

4. Process the HTTP response:

if (response.IsSuccessStatusCode)
{
    string responseBody = await response.Content.ReadAsStringAsync();
    // Process the response body
}
else
{
    string errorMessage = $"HTTP error: {response.StatusCode}";
    // Handle the error
}



Note that HttpClient is disposable, so you should dispose of it when you're done using it. Also, you should consider using the using statement to ensure that the HttpClient is disposed of properly.

No comments:

Post a Comment

Please keep your comments relevant.
Comments with external links and adult words will be filtered.