跳至页脚内容
.NET 帮助

C# HttpClient(开发者用法)

HttpClient 类是 .NET 框架的一部分,它提供了发送 HTTP 请求和从由 URI 标识的资源接收 HTTP 响应的方法。 无论是执行 GET、POST、PUT 或 DELETE 请求,它都简化了 HTTP 请求调用。 本指南将涵盖 HttpClient 在实际场景中的基本使用,并介绍 IronPDF 库。

创建新的 HttpClient 实例

HttpClient 类用于发送 HTTP 请求。 您可以如下创建一个新的实例:

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

在此示例中:

  • 使用 var client = new HttpClient() 创建一个新的 HttpClient 实例。
  • 使用 GetAsync 方法发送 HTTP GET 请求。
  • HttpResponseMessage 存储在 var response 中。
  • 响应的内容使用 response.Content.ReadAsStringAsync() 来检索。

发送 HTTP 请求

HTTP GET 请求

要发出 HTTP GET 请求并处理响应:

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
  • IsSuccessStatusCode 属性确保请求成功。
  • 响应正文异步读取,使用 ReadAsStringAsync()

HTTP POST 请求

发送 POST 请求需要添加请求正文:

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 使用指定的正文 (requestBody) 发送请求。
  • 必须指定内容类型 (application/json)。

HTTP PUT 请求

HTTP PUT 请求更新资源:

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 发送一个 PUT 请求以更新指定 URI 的资源。
  • 请求正文通常包含要更新的数据。

HTTP DELETE 请求

要发送 HTTP DELETE 请求:

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 发送一个 DELETE 请求以移除资源。

处理 HTTP 响应

每个 HTTP 请求返回一个 HttpResponseMessage 对象,其中包括响应正文、头信息和状态码。 例如:

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 提供状态码 (例如:200,404)。
  • response.Content 包含响应正文,可以使用 ReadAsStringAsync() 异步读取。

高效使用 HttpClient

应重用 HttpClient 实例以利用连接池并避免耗尽系统资源。 一种典型的模式是为您的应用程序或服务的生命周期创建一个 HttpClient 实例。这可以通过静态变量或者用于 Web 应用程序的依赖注入来完成。

静态 HttpClient 示例

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

HttpClient 实例在整个应用中重用,减少创建新的 HTTP 连接的开销。

通过依赖注入使用 HttpClient

在 Web 应用程序中,推荐的方法是将 HttpClient 注册为单例服务:

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

您还可以创建命名客户端和类型化客户端以进行更具体的配置。

连接池和代理设置

通过重用 HttpClient 实例,您可以从连接池中受益,这改善了对同一服务器的多个请求的性能。 您还可以使用 HttpClientHandler 类配置代理设置:

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

错误处理和状态码

要处理不同的 HTTP 状态码,请检查 HttpResponseMessage.StatusCode 属性:

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 响应体处理

您经常处理 JSON 响应。 您可以将响应内容反序列化为强类型对象:

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

ReadAsStringAsync() 方法简化了直接将 JSON 内容读取到 C# 对象中。

IronPDF 简介

C# HttpClient(对开发人员的工作原理):图 1 - IronPDF

IronPDF 是一个 .NET PDF 库,专为在 C# 中创建、操作和转换 PDF 文件而设计。 它广泛用于从 HTML、CSS、JavaScript 以及其他格式生成高质量 PDF。 IronPDF 提供了 HTML 到 PDF 转换、PDF 合并、水印以及高级操作如数字签名和 PDF 加密等功能。 它兼容各种平台,包括 Windows、Linux 和 macOS,使其成为跨平台开发的多功能解决方案。

将 IronPDF 与 HttpClient 一起使用

在 C# 中组合使用 IronPDF 和 HttpClient 类是动态生成和操作来自 Web 资源的 PDF 文档的有效方式。 例如,您可以通过 HttpClient 从 URL 检索 HTML 内容,然后使用 IronPDF 将该 HTML 转换为 PDF 文档。 当基于实时 Web 内容动态生成报告、发票或任何文档时,这非常有用。

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(对开发人员的工作原理):图 2 - PDF 输出

使用真实的天气 API 时,请记得用 API 密钥替换“YOUR_API_KEY”。

结论

C# HttpClient(对开发人员的工作原理):图 3 - 许可

本教程探讨了在 C# 中使用 HttpClient 类来发送 HTTP 请求和处理响应。 我们还介绍了 IronPDF,这是一个强大的 .NET 应用程序 PDF 生成库。 我们演示了如何通过 HttpClient 从 Web 服务检索 HTML 内容并使用 IronPDF 将其转换为 PDF,从而结合使用这些技术。

IronPDF 提供免费试用,其许可证起价为 $799,使其成为寻求全面 PDF 生成功能的开发人员的有价值工具。

常见问题解答

如何将 HTML 内容转换为 C# 中的 PDF?

您可以使用 IronPDF 利用其方法(如 RenderHtmlAsPdf)将 HTML 内容转换为 PDF。这使您可以轻松地将 HTML 字符串,包括 CSS 和 JavaScript,转换为专业的 PDF 文档。

如何在 C# 中结合 HttpClient 与 PDF 生成?

通过将 HttpClient 与 IronPDF 集成,您可以从网络资源检索 HTML 内容,然后使用 IronPDF 的转换方法将该内容转换为 PDF 文档。这对从实时数据生成报告或发票特别有用。

重用 HttpClient 实例的重要性是什么?

重用 HttpClient 实例对于高效的资源管理至关重要。它利用连接池,减少为每个请求创建新连接的开销,从而提高应用程序的性能。

如何在 C# 中反序列化 JSON 响应?

在 C# 中,可以使用 JsonSerializer 类反序列化 JSON 响应。在将响应内容检索为字符串后,可以使用 JsonSerializer.Deserialize 将其转换为强类型的 C# 对象。

在 C# 中处理 HTTP 状态代码的最佳实践是什么?

在 C# 中处理 HTTP 状态代码涉及检查 HttpResponseMessageStatusCode 属性。使用条件语句管理特定代码,例如 HttpStatusCode.OKHttpStatusCode.NotFound,以实现适当的错误处理。

IronPDF 如何通过 PDF 功能增强 .NET 应用程序?

IronPDF 通过提供强大的工具来创建、操作和转换 PDF 文件,从而增强了 .NET 应用程序。它支持从 HTML、CSS 和 JavaScript 生成高质量的 PDF,提供给开发人员轻松生成动态文档的能力。

我可以使用 HttpClient 获取用于 PDF 转换的 HTML 内容吗?

是的,HttpClient 可以从网络资源获取 HTML 内容,然后可以使用 IronPDF 将该内容转换为 PDF。这种方法非常适合从实时 Web 数据或动态内容生成 PDF。

如何在 C# 中为 HttpClient 配置代理设置?

要为 HttpClient 配置代理设置,可以使用 HttpClientHandler 类。在创建 HttpClient 实例时,将 Proxy 属性设置为 WebProxy 实例,并启用 UseProxy 选项。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。