.NET 帮助 C# HttpClient(开发者用法) Jacob Mellor 已更新:2025年6月22日 下载 IronPDF NuGet 下载 DLL 下载 Windows 安装程序 免费试用 LLM副本 LLM副本 将页面复制为 Markdown 格式,用于 LLMs 在 ChatGPT 中打开 向 ChatGPT 咨询此页面 在双子座打开 向 Gemini 询问此页面 在 Grok 中打开 向 Grok 询问此页面 打开困惑 向 Perplexity 询问有关此页面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 复制链接 电子邮件文章 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); } } $vbLabelText $csharpLabel 在此示例中: 使用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); } } } 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); } } } $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); } } } $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); } } } $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"); } } } $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}"); } } } $vbLabelText $csharpLabel 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; } public static class HttpClientProvider { private static readonly HttpClient client = new HttpClient(); public static HttpClient Client => client; } $vbLabelText $csharpLabel HttpClient 实例在整个应用中重用,减少创建新的 HTTP 连接的开销。 通过依赖注入使用 HttpClient 在 Web 应用程序中,推荐的方法是将 HttpClient 注册为单例服务: public void ConfigureServices(IServiceCollection services) { services.AddHttpClient(); } public void ConfigureServices(IServiceCollection services) { services.AddHttpClient(); } $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); $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}"); } } $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; } } $vbLabelText $csharpLabel 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}"); } } } $vbLabelText $csharpLabel 使用真实的天气 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 选项。 Jacob Mellor 立即与工程团队聊天 首席技术官 Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。Jacob 拥有曼彻斯特大学土木工程一级荣誉工程学士学位(BEng)(1998-2001 年)。他的旗舰产品 IronPDF 和 Iron Suite for .NET 库在全球的 NuGet 安装量已超过 3000 万次,其基础代码继续为全球使用的开发人员工具提供动力。Jacob 拥有 25 年的商业经验和 41 年的编码专业知识,他一直专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。 相关文章 已更新2026年2月20日 架起 CLI 简洁性与 .NET 的桥梁:使用 IronPDF for .NET 的 Curl DotNet Jacob Mellor 通过 CurlDotNet 填补了这一空白,CurlDotNet 库的创建是为了将 cURL 的熟悉感带入 .NET 生态系统。 阅读更多 已更新2025年12月20日 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多 已更新2025年12月20日 C# String Equals(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 C# AES 加密(开发者如何使用)C# 区别联合(开发者用法)
已更新2026年2月20日 架起 CLI 简洁性与 .NET 的桥梁:使用 IronPDF for .NET 的 Curl DotNet Jacob Mellor 通过 CurlDotNet 填补了这一空白,CurlDotNet 库的创建是为了将 cURL 的熟悉感带入 .NET 生态系统。 阅读更多
已更新2025年12月20日 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多