Skip to footer content
.NET HELP

C# HttpClient (How It Works For Developers)

The HttpClient class, part of the .NET framework, provides methods to send HTTP requests and receive HTTP responses from a resource identified by a URI. It simplifies making HTTP request calls, whether you're performing GET, POST, PUT, or DELETE requests. This guide will cover the essential usage of HttpClient in practical scenarios and introduce the IronPDF library.

Creating a New HttpClient Instance

The HttpClient class is used to send HTTP requests. You can create a new instance of it as follows:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using var client = new HttpClient(); // Create a new instance of HttpClient

        // Send a GET request to the specified URI and store the HTTP response
        var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London");

        // Retrieve the response content as a string
        var responseBody = await response.Content.ReadAsStringAsync();

        // Print the response content to the console
        Console.WriteLine(responseBody);
    }
}
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using var client = new HttpClient(); // Create a new instance of HttpClient

        // Send a GET request to the specified URI and store the HTTP response
        var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London");

        // Retrieve the response content as a string
        var responseBody = await response.Content.ReadAsStringAsync();

        // Print the response content to the console
        Console.WriteLine(responseBody);
    }
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		Dim client = New HttpClient() ' Create a new instance of HttpClient

		' Send a GET request to the specified URI and store the HTTP response
		Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London")

		' Retrieve the response content as a string
		Dim responseBody = Await response.Content.ReadAsStringAsync()

		' Print the response content to the console
		Console.WriteLine(responseBody)
	End Function
End Class
$vbLabelText   $csharpLabel

In this example:

  • A new HttpClient instance is created using var client = new HttpClient().
  • An HTTP GET request is sent using the GetAsync method.
  • The HttpResponseMessage is stored in var response.
  • The content of the response is retrieved using response.Content.ReadAsStringAsync().

Sending HTTP Requests

HTTP GET Request

To make an HTTP GET request and handle the response:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Example
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Paris");

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
    }
}
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Example
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Paris");

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
    }
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks

Friend Class Example
	Shared Async Function Main(ByVal args() As String) As Task
		Dim client = New HttpClient()
		Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Paris")

		' Check if the request was successful
		If response.IsSuccessStatusCode Then
			Dim responseBody = Await response.Content.ReadAsStringAsync()
			Console.WriteLine(responseBody)
		End If
	End Function
End Class
$vbLabelText   $csharpLabel
  • The IsSuccessStatusCode property ensures that the request was successful.
  • The response body is read asynchronously with ReadAsStringAsync().

HTTP POST Request

Sending a POST request involves adding a request body:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Example
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        var requestBody = new StringContent("{ \"location\": \"New York\" }", Encoding.UTF8, "application/json");

        // Send the POST request with the specified body
        var response = await client.PostAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
    }
}
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Example
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        var requestBody = new StringContent("{ \"location\": \"New York\" }", Encoding.UTF8, "application/json");

        // Send the POST request with the specified body
        var response = await client.PostAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
    }
}
Imports System
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks

Friend Class Example
	Shared Async Function Main(ByVal args() As String) As Task
		Dim client = New HttpClient()
		Dim requestBody = New StringContent("{ ""location"": ""New York"" }", Encoding.UTF8, "application/json")

		' Send the POST request with the specified body
		Dim response = Await client.PostAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody)

		' Check if the request was successful
		If response.IsSuccessStatusCode Then
			Dim responseBody = Await response.Content.ReadAsStringAsync()
			Console.WriteLine(responseBody)
		End If
	End Function
End Class
$vbLabelText   $csharpLabel
  • PostAsync sends the request with the specified body (requestBody).
  • The content type must be specified (application/json).

HTTP PUT Request

An HTTP PUT request updates resources:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Example
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        var requestBody = new StringContent("{ \"location\": \"Tokyo\", \"days\": 3 }", Encoding.UTF8, "application/json");

        // Send a PUT request to update the resource
        var response = await client.PutAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
    }
}
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Example
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        var requestBody = new StringContent("{ \"location\": \"Tokyo\", \"days\": 3 }", Encoding.UTF8, "application/json");

        // Send a PUT request to update the resource
        var response = await client.PutAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
    }
}
Imports System
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks

Friend Class Example
	Shared Async Function Main(ByVal args() As String) As Task
		Dim client = New HttpClient()
		Dim requestBody = New StringContent("{ ""location"": ""Tokyo"", ""days"": 3 }", Encoding.UTF8, "application/json")

		' Send a PUT request to update the resource
		Dim response = Await client.PutAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody)

		' Check if the request was successful
		If response.IsSuccessStatusCode Then
			Dim responseBody = Await response.Content.ReadAsStringAsync()
			Console.WriteLine(responseBody)
		End If
	End Function
End Class
$vbLabelText   $csharpLabel
  • PutAsync sends a PUT request to update the resource at the specified URI.
  • The request body typically contains the data to be updated.

HTTP DELETE Request

To send an HTTP DELETE request:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Example
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();

        // Send a DELETE request to remove the resource
        var response = await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY");

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine("Resource deleted successfully");
        }
    }
}
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Example
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();

        // Send a DELETE request to remove the resource
        var response = await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY");

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine("Resource deleted successfully");
        }
    }
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks

Friend Class Example
	Shared Async Function Main(ByVal args() As String) As Task
		Dim client = New HttpClient()

		' Send a DELETE request to remove the resource
		Dim response = Await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY")

		' Check if the request was successful
		If response.IsSuccessStatusCode Then
			Console.WriteLine("Resource deleted successfully")
		End If
	End Function
End Class
$vbLabelText   $csharpLabel
  • DeleteAsync sends a DELETE request to remove the resource.

Handling HTTP Responses

Each HTTP request returns an HttpResponseMessage object, which includes the response body, headers, and status code. For example:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Example
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Sydney");

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        else
        {
            Console.WriteLine($"Error: {response.StatusCode}");
        }
    }
}
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Example
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Sydney");

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        else
        {
            Console.WriteLine($"Error: {response.StatusCode}");
        }
    }
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks

Friend Class Example
	Shared Async Function Main(ByVal args() As String) As Task
		Dim client = New HttpClient()
		Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Sydney")

		' Check if the request was successful
		If response.IsSuccessStatusCode Then
			Dim responseBody = Await response.Content.ReadAsStringAsync()
			Console.WriteLine(responseBody)
		Else
			Console.WriteLine($"Error: {response.StatusCode}")
		End If
	End Function
End Class
$vbLabelText   $csharpLabel
  • Response.StatusCode provides the status code (e.g., 200, 404).
  • response.Content contains the response body, which can be read asynchronously using ReadAsStringAsync().

Efficient Usage of HttpClient

HttpClient instances should be reused to exploit connection pooling and avoid exhausting system resources. A typical pattern is to create a single HttpClient instance for the lifetime of your application or service. This can be done using a static variable or dependency injection for web applications.

Static HttpClient Example

public static class HttpClientProvider
{
    private static readonly HttpClient client = new HttpClient();
    public static HttpClient Client => client;
}
public static class HttpClientProvider
{
    private static readonly HttpClient client = new HttpClient();
    public static HttpClient Client => client;
}
Public Module HttpClientProvider
'INSTANT VB NOTE: The field client was renamed since Visual Basic does not allow fields to have the same name as other class members:
	Private ReadOnly client_Conflict As New HttpClient()
	Public ReadOnly Property Client() As HttpClient
		Get
			Return client_Conflict
		End Get
	End Property
End Module
$vbLabelText   $csharpLabel

The HttpClient instance is reused across the application, reducing the overhead of creating new HTTP connections.

Using HttpClient with Dependency Injection

In a web application, the recommended approach is to register HttpClient as a singleton service:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient();
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient();
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	services.AddHttpClient()
End Sub
$vbLabelText   $csharpLabel

You can also create named clients and typed clients for more specific configurations.

Connection Pooling and Proxy Settings

By reusing HttpClient instances, you benefit from connection pooling, which improves the performance of multiple requests to the same server. You can also configure proxy settings using the HttpClientHandler class:

using System.Net;
using System.Net.Http;

var handler = new HttpClientHandler
{
    Proxy = new WebProxy("http://proxyserver:port"), // Set the proxy server
    UseProxy = true
};

var client = new HttpClient(handler);
using System.Net;
using System.Net.Http;

var handler = new HttpClientHandler
{
    Proxy = new WebProxy("http://proxyserver:port"), // Set the proxy server
    UseProxy = true
};

var client = new HttpClient(handler);
Imports System.Net
Imports System.Net.Http

Private handler = New HttpClientHandler With {
	.Proxy = New WebProxy("http://proxyserver:port"),
	.UseProxy = True
}

Private client = New HttpClient(handler)
$vbLabelText   $csharpLabel

Error Handling and Status Codes

To handle different HTTP status codes, check the HttpResponseMessage.StatusCode property:

using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

async Task MakeRequestAsync()
{
    try
    {
        using var client = new HttpClient();
        var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Berlin");

        // Handle the response based on the status code
        switch (response.StatusCode)
        {
            case HttpStatusCode.OK:
                Console.WriteLine("Success");
                var content = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"Response content: {content}");
                break;
            case HttpStatusCode.NotFound:
                Console.WriteLine("Resource not found");
                break;
            case HttpStatusCode.Unauthorized:
                Console.WriteLine("Unauthorized access");
                break;
            case HttpStatusCode.InternalServerError:
                Console.WriteLine("Server error occurred");
                break;
            default:
                Console.WriteLine($"Unexpected status code: {response.StatusCode}");
                break;
        }
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine($"Request error: {e.Message}");
    }
    catch (Exception e)
    {
        Console.WriteLine($"An error occurred: {e.Message}");
    }
}
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

async Task MakeRequestAsync()
{
    try
    {
        using var client = new HttpClient();
        var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Berlin");

        // Handle the response based on the status code
        switch (response.StatusCode)
        {
            case HttpStatusCode.OK:
                Console.WriteLine("Success");
                var content = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"Response content: {content}");
                break;
            case HttpStatusCode.NotFound:
                Console.WriteLine("Resource not found");
                break;
            case HttpStatusCode.Unauthorized:
                Console.WriteLine("Unauthorized access");
                break;
            case HttpStatusCode.InternalServerError:
                Console.WriteLine("Server error occurred");
                break;
            default:
                Console.WriteLine($"Unexpected status code: {response.StatusCode}");
                break;
        }
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine($"Request error: {e.Message}");
    }
    catch (Exception e)
    {
        Console.WriteLine($"An error occurred: {e.Message}");
    }
}
Imports System
Imports System.Net
Imports System.Net.Http
Imports System.Threading.Tasks

Async Function MakeRequestAsync() As Task
	Try
		Dim client = New HttpClient()
		Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Berlin")

		' Handle the response based on the status code
		Select Case response.StatusCode
			Case HttpStatusCode.OK
				Console.WriteLine("Success")
				Dim content = Await response.Content.ReadAsStringAsync()
				Console.WriteLine($"Response content: {content}")
			Case HttpStatusCode.NotFound
				Console.WriteLine("Resource not found")
			Case HttpStatusCode.Unauthorized
				Console.WriteLine("Unauthorized access")
			Case HttpStatusCode.InternalServerError
				Console.WriteLine("Server error occurred")
			Case Else
				Console.WriteLine($"Unexpected status code: {response.StatusCode}")
		End Select
	Catch e As HttpRequestException
		Console.WriteLine($"Request error: {e.Message}")
	Catch e As Exception
		Console.WriteLine($"An error occurred: {e.Message}")
	End Try
End Function
$vbLabelText   $csharpLabel

JSON Response Body Handling

You often work with JSON responses. You can deserialize the response content into a strongly typed object:

using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

class Example
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London");
        var jsonString = await response.Content.ReadAsStringAsync();

        // Deserialize the JSON response into a WeatherResponse object
        var weatherResponse = JsonSerializer.Deserialize<WeatherResponse>(jsonString);

        Console.WriteLine($"Location: {weatherResponse.Location}, Temperature: {weatherResponse.Temperature}");
    }
}

public class WeatherResponse
{
    public string Location { get; set; }
    public double Temperature { get; set; }
}
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

class Example
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London");
        var jsonString = await response.Content.ReadAsStringAsync();

        // Deserialize the JSON response into a WeatherResponse object
        var weatherResponse = JsonSerializer.Deserialize<WeatherResponse>(jsonString);

        Console.WriteLine($"Location: {weatherResponse.Location}, Temperature: {weatherResponse.Temperature}");
    }
}

public class WeatherResponse
{
    public string Location { get; set; }
    public double Temperature { get; set; }
}
Imports System
Imports System.Net.Http
Imports System.Text.Json
Imports System.Threading.Tasks

Friend Class Example
	Shared Async Function Main(ByVal args() As String) As Task
		Dim client = New HttpClient()
		Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London")
		Dim jsonString = Await response.Content.ReadAsStringAsync()

		' Deserialize the JSON response into a WeatherResponse object
		Dim weatherResponse = JsonSerializer.Deserialize(Of WeatherResponse)(jsonString)

		Console.WriteLine($"Location: {weatherResponse.Location}, Temperature: {weatherResponse.Temperature}")
	End Function
End Class

Public Class WeatherResponse
	Public Property Location() As String
	Public Property Temperature() As Double
End Class
$vbLabelText   $csharpLabel

The ReadAsStringAsync() method simplifies reading JSON content directly into C# objects.

Introducing IronPDF

C# HttpClient (How It Works For Developers): Figure 1 - IronPDF

IronPDF is a .NET PDF library designed to create, manipulate, and convert PDF files in C#. It is widely used for generating high-quality PDFs from HTML, CSS, JavaScript, and other formats. IronPDF offers features such as HTML to PDF conversion, PDF merging, watermarking, and even advanced operations like digital signatures and PDF encryption. It's compatible with various platforms, including Windows, Linux, and macOS, making it a versatile solution for cross-platform development.

Using IronPDF with HttpClient

Combining IronPDF with the HttpClient class in C# is an effective way to generate and manipulate PDF documents from web resources dynamically. For instance, you can retrieve HTML content from a URL via HttpClient and then convert this HTML into a PDF document using IronPDF. This is useful when generating reports, invoices, or any document dynamically based on live web content.

using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using IronPdf;

class Program
{
    static async Task Main(string[] args)
    {
        License.LicenseKey = "YOUR_LICENSE_KEY"; // Set your IronPDF license key
        using var client = new HttpClient();
        var response = await client.GetAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY&q=London&days=3");

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            var jsonContent = await response.Content.ReadAsStringAsync();
            var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonContent);

            // Format the JSON content for pretty-printing
            var formattedJson = JsonSerializer.Serialize(jsonElement, new JsonSerializerOptions { WriteIndented = true });

            // Escape the JSON for HTML
            formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson);

            // Create an HTML string for PDF generation
            var htmlContent = $@"
            <html>
            <head>
                <style>
                    body {{ font-family: Arial, sans-serif; }}
                    pre {{ background-color: #f4f4f4; padding: 20px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; }}
                </style>
            </head>
            <body>
                <h1>Weather Forecast (JSON Data)</h1>
                <pre>{formattedJson}</pre>
            </body>
            </html>";

            // Generate the PDF from the HTML content
            var renderer = new ChromePdfRenderer();
            var pdf = renderer.RenderHtmlAsPdf(htmlContent);

            // Save the PDF to a file
            pdf.SaveAs("F://weather_report.pdf");

            Console.WriteLine("PDF generated successfully!");
        }
        else
        {
            Console.WriteLine($"Failed to retrieve content. Status code: {response.StatusCode}");
        }
    }
}
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using IronPdf;

class Program
{
    static async Task Main(string[] args)
    {
        License.LicenseKey = "YOUR_LICENSE_KEY"; // Set your IronPDF license key
        using var client = new HttpClient();
        var response = await client.GetAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY&q=London&days=3");

        // Check if the request was successful
        if (response.IsSuccessStatusCode)
        {
            var jsonContent = await response.Content.ReadAsStringAsync();
            var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonContent);

            // Format the JSON content for pretty-printing
            var formattedJson = JsonSerializer.Serialize(jsonElement, new JsonSerializerOptions { WriteIndented = true });

            // Escape the JSON for HTML
            formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson);

            // Create an HTML string for PDF generation
            var htmlContent = $@"
            <html>
            <head>
                <style>
                    body {{ font-family: Arial, sans-serif; }}
                    pre {{ background-color: #f4f4f4; padding: 20px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; }}
                </style>
            </head>
            <body>
                <h1>Weather Forecast (JSON Data)</h1>
                <pre>{formattedJson}</pre>
            </body>
            </html>";

            // Generate the PDF from the HTML content
            var renderer = new ChromePdfRenderer();
            var pdf = renderer.RenderHtmlAsPdf(htmlContent);

            // Save the PDF to a file
            pdf.SaveAs("F://weather_report.pdf");

            Console.WriteLine("PDF generated successfully!");
        }
        else
        {
            Console.WriteLine($"Failed to retrieve content. Status code: {response.StatusCode}");
        }
    }
}
Imports System
Imports System.Net.Http
Imports System.Text.Json
Imports System.Threading.Tasks
Imports IronPdf

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		License.LicenseKey = "YOUR_LICENSE_KEY" ' Set your IronPDF license key
		Dim client = New HttpClient()
		Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY&q=London&days=3")

		' Check if the request was successful
		If response.IsSuccessStatusCode Then
			Dim jsonContent = Await response.Content.ReadAsStringAsync()
			Dim jsonElement = JsonSerializer.Deserialize(Of JsonElement)(jsonContent)

			' Format the JSON content for pretty-printing
			Dim formattedJson = JsonSerializer.Serialize(jsonElement, New JsonSerializerOptions With {.WriteIndented = True})

			' Escape the JSON for HTML
			formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson)

			' Create an HTML string for PDF generation
			Dim htmlContent = $"
            <html>
            <head>
                <style>
                    body {{ font-family: Arial, sans-serif; }}
                    pre {{ background-color: #f4f4f4; padding: 20px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; }}
                </style>
            </head>
            <body>
                <h1>Weather Forecast (JSON Data)</h1>
                <pre>{formattedJson}</pre>
            </body>
            </html>"

			' Generate the PDF from the HTML content
			Dim renderer = New ChromePdfRenderer()
			Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)

			' Save the PDF to a file
			pdf.SaveAs("F://weather_report.pdf")

			Console.WriteLine("PDF generated successfully!")
		Else
			Console.WriteLine($"Failed to retrieve content. Status code: {response.StatusCode}")
		End If
	End Function
End Class
$vbLabelText   $csharpLabel

C# HttpClient (How It Works For Developers): Figure 2 - PDF Output

Remember to replace "YOUR_API_KEY" with an API key when using a real weather API.

Conclusion

C# HttpClient (How It Works For Developers): Figure 3 - Licensing

This tutorial explored using the HttpClient class in C# to send HTTP requests and handle responses. We also introduced IronPDF, a powerful library for generating PDFs in .NET applications. We demonstrated how to combine these technologies by retrieving HTML content from a web service using HttpClient and converting it to PDF using IronPDF.

IronPDF offers a free trial, and its licenses start at $749, making it a valuable tool for developers seeking comprehensive PDF generation capabilities.

Frequently Asked Questions

What is the HttpClient class in C#?

The HttpClient class is part of the .NET framework and provides methods to send HTTP requests and receive HTTP responses from a resource identified by a URI. It simplifies making HTTP request calls, such as GET, POST, PUT, and DELETE.

How do you create a new instance of HttpClient?

You can create a new instance of HttpClient by declaring it using 'var client = new HttpClient();'. This instance can be used to send HTTP requests.

How can I send a GET request using HttpClient?

To send a GET request using HttpClient, use the 'GetAsync' method. For example, 'var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London");'. You can then check the response's success status and read the content.

How is a POST request sent using HttpClient?

A POST request is sent using the 'PostAsync' method along with a request body. You need to create a StringContent object for the request body and specify the content type, such as JSON.

What is the recommended way to use HttpClient efficiently?

To efficiently use HttpClient, it's recommended to reuse instances across the application's lifetime to take advantage of connection pooling. This can be achieved through static variables or by using dependency injection in web applications.

How can I handle different HTTP status codes in C#?

You can handle different HTTP status codes by checking the StatusCode property of the HttpResponseMessage. Use a switch or if-else statements to handle specific codes, like HttpStatusCode.OK or HttpStatusCode.NotFound.

How can I generate PDFs from HTML content retrieved via HTTP requests?

You can use the IronPDF library, a .NET library used to create, manipulate, and convert PDF files. It can be integrated with HttpClient to generate PDFs from HTML content retrieved via HTTP requests, which is useful for creating dynamic documents based on live web content.

Can I deserialize JSON responses using HttpClient in C#?

Yes, you can deserialize JSON responses using the JsonSerializer class in C#. After reading the response content as a string, use 'JsonSerializer.Deserialize' to convert it into a strongly typed object.

How do you configure proxy settings for HttpClient?

Proxy settings for HttpClient can be configured using the HttpClientHandler class. Set the Proxy property to a WebProxy instance and enable the UseProxy option when creating the HttpClient instance.

What are the benefits of reusing HttpClient instances?

Reusing HttpClient instances benefits performance by leveraging connection pooling, reducing the overhead of creating new connections for each request, and avoiding resource exhaustion.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.