Site icon JD Bots

How to Call API using C# with Headers and Body?

woman writing on whiteboard

Photo by ThisIsEngineering on Pexels.com

HttpClient class from the .NET framework. Here is an example of how you might use the HttpClient class to call an API with headers and a request body:

using System.Net.Http;
using System.Collections.Generic;

// ...

// create an instance of the HttpClient class
var client = new HttpClient();

// specify the API endpoint you want to call
var url = "http://example.com/api/endpoint";

// create a dictionary to hold the request headers
var headers = new Dictionary<string, string>();

// add the headers to the dictionary
headers.Add("header1", "value1");
headers.Add("header2", "value2");

// create the request body as a string
var body = "{\"key1\":\"value1\",\"key2\":\"value2\"}";

// create a new HttpRequestMessage object with the specified method, url, and body
var request = new HttpRequestMessage(HttpMethod.Post, url)
{
    Content = new StringContent(body)
};

// add the headers to the request
foreach (var header in headers)
{
    request.Headers.Add(header.Key, header.Value);
}

// make the API call using the SendAsync method of the HttpClient
var response = await client.SendAsync(request);

// check the status code of the response to make sure the call was successful
if (response.IsSuccessStatusCode)
{
    // if the call was successful, read the response content
    var content = await response.Content.ReadAsStringAsync();

    // do something with the response content
    // ...
}

Thank you!!!

Exit mobile version