.NET幫助 C# HttpClient(對開發者如何理解的工作) Curtis Chau 更新日期:6月 22, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article HttpClient 類別,作為 .NET 框架的一部分,提供了向由 URI 識別的資源發送 HTTP 請求和接收 HTTP 響應的方法。 它簡化了 HTTP 請求呼叫,不管您是在執行 GET、POST、PUT 還是 DELETE 請求。 本指南將介紹 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 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 記得當使用真實的天氣 API 時,用 API 密鑰替換 "YOUR_API_KEY"。 結論 本教程探索了在 C# 中使用 HttpClient 類來發送 HTTP 請求和處理響應。 我們還介紹了 IronPDF,一個在 .NET 應用程序中生成 PDF 的強大庫。 我們演示了如何通過 HttpClient 從 Web 服務檢索 HTML 內容並使用 IronPDF 將其轉換為 PDF 來結合這些技術。 IronPDF 提供免費試用,其許可證開始於 $799,對於尋求全面 PDF 生成能力的開發者來說是有價值的工具。 常見問題解答 如何在 C# 中將 HTML 內容轉換為 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 獲取 HTML 內容以進行 PDF 轉換嗎? 是的,HttpClient 可以從網路資源獲取 HTML 內容,然後可以使用 IronPDF 將其轉換為 PDF。這種方法非常適合從即時網頁數據或動態內容生成 PDF。 如何在 C# 中配置 HttpClient 的代理設置? 要配置 HttpClient 的代理設置,可以使用 HttpClientHandler 類。在創建 HttpClient 實例時,將 Proxy 屬性設置為 WebProxy 實例並啟用 UseProxy 選項。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# AES加密(對開發者如何理解的工作)C#差異聯合(對開發者如何...