.NET 帮助

C# HttpClient(面向开发人员的工作原理)

雷根·彭
雷根·彭
2024年十月23日
分享:

"(《世界人权宣言》)HttpClient 类HTTP 服务器是 .NET Framework 的一部分,提供了从 URI 标识的资源发送 HTTP 请求和接收 HTTP 响应的方法。 它简化了 HTTP 请求调用,无论您是执行 GET、POST 请求、PUT 还是 DELETE 请求。 本指南将涵盖 HttpClient 在实际场景中的基本用法,并介绍IronPDF 库.

创建新的 HttpClient 实例

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

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

在此示例中:

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

发送 HTTP 请求

HTTP GET 请求

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

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);
}
  • IsSuccessStatusCode 属性可确保请求成功。
  • 使用 ReadAsStringAsync 异步读取响应体。

HTTP POST 请求

发送 POST 请求涉及添加请求正文:

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);
}
  • PostAsync 发送带有指定正文的请求(请求正文).
  • 您必须指定内容类型(应用程序/JSON).

HTTP PUT 请求

HTTP PUT 请求更新资源:

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

HTTP DELETE 请求

发送 HTTP DELETE 请求:

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");
}
  • DeleteAsync 发送 DELETE 请求以删除资源。

处理 HTTP 响应

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

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

高效使用 HttpClient

HttpClient 实例应重复使用,以利用连接池,避免耗尽系统资源。 一种典型的模式是为应用程序或服务的整个生命周期创建一个 HttpClient 实例。这可以通过静态变量或网络应用程序的依赖注入来实现。

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

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

通过依赖注入使用 HttpClient

在网络应用程序中,建议将 HttpClient 注册为单例服务:

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

您还可以创建命名客户端和键入客户端,以进行更具体的配置。

连接池和代理设置

通过重复使用 HttpClient 实例,您可以从连接池中获益,从而提高向同一服务器发出多个请求的性能。 您还可以使用 HttpClientHandler 类配置代理设置:

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

错误处理和状态代码

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

JSON 响应体处理

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

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

ReadAsStringAsync 方法简化了将 JSON 内容直接读入 C# 对象的过程。

介绍IronPDF

C# HttpClient(如何为开发人员工作):图 1 - IronPdf

IronPDF for .NET 是一个 .NET PDF 库,旨在用 C# 创建、操作和转换 PDF 文件。 它广泛用于从 HTML 生成高质量 PDF翻译的格式包括:.NET、CSS、JavaScript 和其他格式。 IronPDF 提供 HTML 到 PDF 的转换、PDF 合并、水印等功能,甚至还有数字签名和 PDF 加密等高级操作。 它兼容各种平台,包括 Windows、Linux 和 macOS,是跨平台开发的通用解决方案。

使用 IronPDF 和 HttpClient

将 IronPDF 与 C# 中的 HttpClient 类相结合,是动态生成和处理来自网络资源的 PDF 文档的有效方法。 例如,您可以通过 HttpClient 从 URL 获取 HTML 内容,然后使用 IronPdf 将此 HTML 转换为 PDF 文档。 这在根据实时网络内容动态生成报告、发票或任何文档时非常有用。

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

C# HttpClient(如何为开发人员工作):图 2 - PDF 输出

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

结论

C# HttpClient(如何为开发人员工作):图 3 - 许可证

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

IronPDF提供免费试用,其许可证起价为$749,对于寻求全面PDF生成功能的开发者来说是一个有价值的工具。

雷根·彭
软件工程师
Regan毕业于雷丁大学,拥有电子工程学士学位。在加入Iron Software之前,他的前工作职位要求他专注于单一任务;他在Iron Software最喜欢的是能进行多种工作,无论是增加销售价值、技术支持、产品开发还是营销。他喜欢了解开发人员如何使用Iron Software的库,并利用这些知识不断改进文档和开发产品。
< 前一页
C# AES 加密(如何为开发人员工作)
下一步 >
C# 歧义联盟(如何为开发人员工作)