IRONSOFTWAREHOME
开发者更新

C# HttpClient(开发者用法)

Jacob Mellor,Team Iron 的首席技术官
Jacob Mellor
Updated: 2026年4月21日

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);
    }
}

在此示例中:

  • 使用var client = new HttpClient()创建了一个新的HttpClient实例。
  • 使用GetAsync方法发送HTTP GET请求。
  • 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);
        }
    }
}
  • 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);
        }
    }
}
  • 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);
        }
    }
}
  • 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");
        }
    }
}
  • 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}");
        }
    }
}
  • Response.StatusCode提供状态码(例如,200,404)。
  • ReadAsStringAsync()异步读取。

高效使用 HttpClient

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

静态 HttpClient 示例

public static class HttpClientProvider
{
    private static readonly HttpClient client = new HttpClient();
    public static HttpClient Client => client;
}

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

通过依赖注入使用 HttpClient

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

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient();
}

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

连接池和代理设置

通过重用 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);

错误处理和状态码

要处理不同的 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}");
    }
}

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; }
}

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}");
        }
    }
}
C#

C# HttpClient(开发者的工作原理):图2 - PDF输出

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

结论

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

IronPDF提供免费试用,许可证起价$999,使其成为寻求全面PDF生成功能的开发者的宝贵工具。

Jacob Mellor,Team Iron 的首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。

相关文章

Key in blue circle

立即获取免费的 30 天试用版密钥

Your trial license will be sent to your email address

无任何限制。100% 解锁。无需信用卡。

bullet_checked无需信用卡或创建账户无任何限制。100% 解锁。无需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
预约您的免费现场演示
Booking Badge

深受全球数百万工程师信赖

Iron Software 的客户徽标
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥
无需信用卡或创建账户