Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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 request, PUT, or DELETE requests. This guide will cover the essential usage of HttpClient in practical scenarios and introduce the IronPDF library.
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;
class Program
{
static async Task Main(string[] args)
{
using var client = new HttpClient(); //HttpClient client
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London"); // HTTP response for GET request
var responseBody = await response.Content.ReadAsStringAsync(); // response content
Console.WriteLine(responseBody);
}
}
using System;
using System.Net.Http;
class Program
{
static async Task Main(string[] args)
{
using var client = new HttpClient(); //HttpClient client
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London"); // HTTP response for GET request
var responseBody = await response.Content.ReadAsStringAsync(); // response content
Console.WriteLine(responseBody);
}
}
Imports System
Imports System.Net.Http
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient() 'HttpClient client
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London") ' HTTP response for GET request
Dim responseBody = Await response.Content.ReadAsStringAsync() ' response content
Console.WriteLine(responseBody)
End Function
End Class
In this example:
To make an HTTP GET request and handle the response:
var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Paris");
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Paris");
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
Dim client = New HttpClient()
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Paris")
If response.IsSuccessStatusCode Then
Dim responseBody = Await response.Content.ReadAsStringAsync()
Console.WriteLine(responseBody)
End If
Sending a POST request involves adding a request body:
var client = new HttpClient();
var requestBody = new StringContent("{ \"location\": \"New York\" }", Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
var client = new HttpClient();
var requestBody = new StringContent("{ \"location\": \"New York\" }", Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
Dim client = New HttpClient()
Dim requestBody = New StringContent("{ ""location"": ""New York"" }", Encoding.UTF8, "application/json")
Dim response = Await client.PostAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody)
If response.IsSuccessStatusCode Then
Dim responseBody = Await response.Content.ReadAsStringAsync()
Console.WriteLine(responseBody)
End If
An HTTP PUT request updates resources:
var client = new HttpClient();
var requestBody = new StringContent("{ \"location\": \"Tokyo\", \"days\": 3 }", Encoding.UTF8, "application/json");
var response = await client.PutAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
var client = new HttpClient();
var requestBody = new StringContent("{ \"location\": \"Tokyo\", \"days\": 3 }", Encoding.UTF8, "application/json");
var response = await client.PutAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
Dim client = New HttpClient()
Dim requestBody = New StringContent("{ ""location"": ""Tokyo"", ""days"": 3 }", Encoding.UTF8, "application/json")
Dim response = Await client.PutAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody)
If response.IsSuccessStatusCode Then
Dim responseBody = Await response.Content.ReadAsStringAsync()
Console.WriteLine(responseBody)
End If
To send an HTTP DELETE request:
var client = new HttpClient();
var response = await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Resource deleted successfully");
}
var client = new HttpClient();
var response = await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Resource deleted successfully");
}
Dim client = New HttpClient()
Dim response = Await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY")
If response.IsSuccessStatusCode Then
Console.WriteLine("Resource deleted successfully")
End If
Each HTTP request returns an HttpResponseMessage object, which includes the response body, headers, and status code. For example:
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Sydney");
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
}
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Sydney");
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
}
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Sydney")
If response.IsSuccessStatusCode Then
Dim responseBody = Await response.Content.ReadAsStringAsync()
Console.WriteLine(responseBody)
Else
Console.WriteLine($"Error: {response.StatusCode}")
End If
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.
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
The HttpClient instance is reused across the application, reducing the overhead of creating new HTTP connections.
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
You can also create named clients and typed clients for more specific configurations.
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:
var handler = new HttpClientHandler
{
Proxy = new WebProxy("http://proxyserver:port"),
UseProxy = true
};
var client = new HttpClient(handler);
var handler = new HttpClientHandler
{
Proxy = new WebProxy("http://proxyserver:port"),
UseProxy = true
};
var client = new HttpClient(handler);
Dim handler = New HttpClientHandler With {
.Proxy = New WebProxy("http://proxyserver:port"),
.UseProxy = True
}
Dim client = New HttpClient(handler)
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");
// Response Status Code Cases
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");
// Response Status Code Cases
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")
' Response Status Code Cases
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
You often work with JSON responses. You can deserialize the response content into a strongly typed object:
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
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();
var weatherResponse = JsonSerializer.Deserialize<WeatherResponse>(jsonString);
public class WeatherResponse
{
public string Location { get; set; }
public double Temperature { get; set; }
}
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
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();
var weatherResponse = JsonSerializer.Deserialize<WeatherResponse>(jsonString);
public class WeatherResponse
{
public string Location { get; set; }
public double Temperature { get; set; }
}
Imports System.Net.Http
Imports System.Text.Json
Imports System.Threading.Tasks
Private client = New HttpClient()
Private response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London")
Private jsonString = await response.Content.ReadAsStringAsync()
Private weatherResponse = JsonSerializer.Deserialize(Of WeatherResponse)(jsonString)
Public Class WeatherResponse
Public Property Location() As String
Public Property Temperature() As Double
End Class
The ReadAsStringAsync method simplifies reading JSON content directly into C# objects.
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.
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.Threading.Tasks;
using System.Text.Json;
using IronPdf;
class Program
{
static async Task Main(string[] args)
{
License.LicenseKey = "IRONSUITE.WINSWRITERSIRONSOFTWARECOM.31102-3E7C9B3308-CIHWVP2-L2A7FVEBUSFN-DP6CI32YVXIN-45HQSAZOBOCW-YCYETGS4ENQX-NZXXG4YCPAYI-EBCIJ43PNLJW-DKWC7U-TFXPQ4LKLXGPEA-DEPLOYMENT.TRIAL-G43TTA.TRIAL.EXPIRES.20.MAY.2025";
using var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/forecast.json?key=55c9040a6ad34c6c90470702240609&q=London&days=3");
if (response.IsSuccessStatusCode)
{
var jsonContent = await response.Content.ReadAsStringAsync();
// Pretty-print the JSON
var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonContent);
var formattedJson = JsonSerializer.Serialize(jsonElement, new JsonSerializerOptions { WriteIndented = true });
// Escape the JSON for HTML
formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson);
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>";
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
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.Threading.Tasks;
using System.Text.Json;
using IronPdf;
class Program
{
static async Task Main(string[] args)
{
License.LicenseKey = "IRONSUITE.WINSWRITERSIRONSOFTWARECOM.31102-3E7C9B3308-CIHWVP2-L2A7FVEBUSFN-DP6CI32YVXIN-45HQSAZOBOCW-YCYETGS4ENQX-NZXXG4YCPAYI-EBCIJ43PNLJW-DKWC7U-TFXPQ4LKLXGPEA-DEPLOYMENT.TRIAL-G43TTA.TRIAL.EXPIRES.20.MAY.2025";
using var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/forecast.json?key=55c9040a6ad34c6c90470702240609&q=London&days=3");
if (response.IsSuccessStatusCode)
{
var jsonContent = await response.Content.ReadAsStringAsync();
// Pretty-print the JSON
var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonContent);
var formattedJson = JsonSerializer.Serialize(jsonElement, new JsonSerializerOptions { WriteIndented = true });
// Escape the JSON for HTML
formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson);
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>";
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
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.Threading.Tasks
Imports System.Text.Json
Imports IronPdf
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
License.LicenseKey = "IRONSUITE.WINSWRITERSIRONSOFTWARECOM.31102-3E7C9B3308-CIHWVP2-L2A7FVEBUSFN-DP6CI32YVXIN-45HQSAZOBOCW-YCYETGS4ENQX-NZXXG4YCPAYI-EBCIJ43PNLJW-DKWC7U-TFXPQ4LKLXGPEA-DEPLOYMENT.TRIAL-G43TTA.TRIAL.EXPIRES.20.MAY.2025"
Dim client = New HttpClient()
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/forecast.json?key=55c9040a6ad34c6c90470702240609&q=London&days=3")
If response.IsSuccessStatusCode Then
Dim jsonContent = Await response.Content.ReadAsStringAsync()
' Pretty-print the JSON
Dim jsonElement = JsonSerializer.Deserialize(Of JsonElement)(jsonContent)
Dim formattedJson = JsonSerializer.Serialize(jsonElement, New JsonSerializerOptions With {.WriteIndented = True})
' Escape the JSON for HTML
formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson)
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>"
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
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
Remember to replace "YOUR_API_KEY" with an API key when using a real weather API.
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.
9 .NET API products for your office documents