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);
}
}在此示例中:
- 使用
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);
}
}
}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);
}
}
}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);
}
}
}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");
}
}
}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}");
}
}
}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;
}HttpClient 实例在整个应用中重用,减少创建新的 HTTP 连接的开销。
通过依赖注入使用 HttpClient
在 Web 应用程序中,推荐的方法是将 HttpClient 注册为单例服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
}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);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}");
}
}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; }
}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 简介

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}");
}
}
}
使用真实的天气 API 时,请记得用 API 密钥替换"YOUR_API_KEY"。
结论

本教程探讨了在 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 状态代码涉及检查 HttpResponseMessage 的 StatusCode 属性。使用条件语句管理特定代码,例如 HttpStatusCode.OK 或 HttpStatusCode.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 选项。








