Skip to content

HttpClient Examples

mozhganEtaati edited this page Oct 10, 2025 · 8 revisions

CURL in String

💡 The examples below use POST requests via the HttpClient extension.

Using HttpRequestMessage

using System;
using System.Net.Http;
using System.Text;
using HttpClientToCurl;

class Program
{
    static void Main()
    {
         string requestBody = /*lang=json,strict*/ @"{""name"":""sara"",""requestId"":10001001,""amount"":20000}";

         var requestUri = "api/test";
         var httpRequestMessage = 
                       new HttpRequestMessage(HttpMethod.Post, requestUri) 
                      { Content = new StringContent(requestBody, Encoding.UTF8,MediaTypeNames.Application.Json) };
        httpRequestMessage.Headers.Add("Authorization", "Bearer 4797c126-3f8a-454a-aff1-96c0220dae61");

        using var httpClient = new HttpClient();
        httpClient.BaseAddress = new Uri("http://localhost:1213/v1/");

        string curl= httpClient.GenerateCurlInString(httpRequestMessage);
        Console.WriteLine("Generated curl command:\n");
        Console.WriteLine(curl);
    }
}

Without HttpRequestMessage

using System;
using System.Net.Http;
using System.Text;
using HttpClientToCurl;

class Program
{
    static void Main()
    {
     var requestObject = new { name = "sara", requestId = 10001001, amount = 20000 };

     JsonContent jsonContent = JsonContent.Create(requestObject);

     var requestUri = "api/test";
     HttpRequestHeaders httpRequestHeaders = new HttpRequestMessage().Headers;
     httpRequestHeaders.Add("Authorization", "Bearer 4797c126-3f8a-454a-aff1-96c0220dae61");

     using var httpClient = new HttpClient();
     httpClient.BaseAddress = new Uri("http://localhost:1213/v1/");

     string curl= httpClient.GenerateCurlInString(
     HttpMethod.Post, requestUri, httpRequestHeaders, jsonContent);
        Console.WriteLine("Generated curl command:\n");
        Console.WriteLine(curl);
    }
}

Without HttpRequestMessage and RequestUri

using System;
using System.Net.Http;
using System.Text;
using HttpClientToCurl;

class Program
{
    static void Main()
    {
     var requestObject = new { name = "sara", requestId = 10001001, amount = 20000, };

     JsonContent jsonContent = JsonContent.Create(requestObject);

     HttpRequestHeaders httpRequestHeaders = new HttpRequestMessage().Headers;
     httpRequestHeaders.Add("Authorization", "Bearer 4797c126-3f8a-454a-aff1-96c0220dae61");

     using var httpClient = new HttpClient();
     httpClient.BaseAddress = new Uri("http://localhost:1213/v1/");


     string curl= httpClient.GenerateCurlInString(
                            httpMethod: HttpMethod.Post, 
                            httpRequestHeaders: httpRequestHeaders, 
                            httpContent: jsonContent,
                            requestUri: string.Empty);

     Console.WriteLine("Generated curl command:\n");
     Console.WriteLine(curl);
    }
}

Without HttpRequestMessage and Headers

using System;
using System.Net.Http;
using System.Text;
using HttpClientToCurl;

class Program
{
    static void Main()
    {
     var requestObject = new { name = "sara", requestId = 10001001, amount = 20000, };

     JsonContent jsonContent = JsonContent.Create(requestObject);

     var requestUri = "api/test";

     using var httpClient = new HttpClient();
     httpClient.BaseAddress = new Uri("http://localhost:1213/v1/");

     string curl = httpClient.GenerateCurlInString(
     httpMethod: HttpMethod.Post, requestUri: requestUri, httpContent: jsonContent);

     Console.WriteLine("Generated curl command:\n");
     Console.WriteLine(curl);
    }
}

CURL in File

using System.Text;
using System.Text.Json;
using HttpClientToCurl;

class Program
{
    static async Task Main()
    {
        var requestUri = "api/test";

        // Create an instance of HttpClient
        HttpClient client = new();
        client.BaseAddress = new Uri("http://localhost:1213/v1/");

        try
        {
            // Create a sample Serialized JSON 
             string requestBody = /*lang=json,strict*/ @"{""name"":""sara"",""requestId"":10001001,""amount"":20000}";

            // Create HttpRequestMessage with the POST verb
            HttpRequestMessage request = new(HttpMethod.Post, requestUri);

            // Set up the request headers
            request.Headers.Add("Authorization", "Bearer YourAccessToken"); // Add any necessary headers

            // Set the request content with the requestBody 
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");

            // Generate a curl command and write it to a file for debugging or testing.
            // This command can be imported into Postman for checking and comparing against all the requirements.
            // Config is the Second and an optional parameter
            client.GenerateCurlInFile(request, config =>
            {
                // Customize file configuration if needed
                config.TurnOn = true; // Enable generating curl command to file
                config.Filename = "curl_commands.txt"; // Specify the file name
                config.Path = "C:\\Path\\To\\Directory"; // Specify the directory path
                config.NeedAddDefaultHeaders = true; // Specify if default headers should be included
            });

            // Send the request
            HttpResponseMessage response = await client.SendAsync(request);

            // Check if the request was successful (status code 200-299)
            if (response.IsSuccessStatusCode)
            {
                // Read and print the response content as a string
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response from the API:\n" + responseBody);
            }
            else
            {
                Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception: {ex.Message}");
        }
    }
}

CURL in Console

using System.Text;
using System.Text.Json;
using HttpClientToCurl;

class Program
{
    static async Task Main()
    {
        var requestUri = "api/test";

        // Create an instance of HttpClient
        HttpClient client = new();
        client.BaseAddress = new Uri("http://localhost:1213/v1/");

        try
        {
            // Create a sample Serialized JSON 
             string requestBody = /*lang=json,strict*/ @"{""name"":""sara"",""requestId"":10001001,""amount"":20000}";

            // Create HttpRequestMessage with the POST verb
            HttpRequestMessage request = new(HttpMethod.Post, requestUri);

            // Set up the request headers
            request.Headers.Add("Authorization", "Bearer YourAccessToken"); // Add any necessary headers

            // Set the request content with the requestBody 
            request.Content = new StringContent(requestBody , Encoding.UTF8, "application/json");

            // Log the curl command for debugging or testing.
            // This generates a curl command that can be imported into Postman.
            // Use it to check and compare against all the requirements.
            // Config is the Second and an optional parameter

            client.GenerateCurlInConsole(request, config => { config.EnableCodeBeautification = true; });

            // Send the request
            HttpResponseMessage response = await client.SendAsync(request);

            // Check if the request was successful (status code 200-299)
            if (response.IsSuccessStatusCode)
            {
                // Read and print the response content as a string
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response from the API:\n" + responseBody);
            }
            else
            {
                Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception: {ex.Message}");
        }
    }
}
Clone this wiki locally