.NET HELP C# HttpClient (How It Works For Developers) Jacob Mellor 更新:2025年6月22日 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 HttpClient class 是 .NET Framework 的一部分,它提供了從 URI 識別的資源發送 HTTP 請求和接收 HTTP 回應的方法。 它簡化了 HTTP 請求的呼叫,無論您是執行 GET、POST、PUT 或 DELETE 請求。 本指南將涵蓋 HttpClient 在實際情境中的基本用法,並介紹 IronPdf 函式庫。 建立新的 HttpClient Instance 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 請求。 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); } } } $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)。 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; } $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 for .NET 是一個 .NET PDF 函式庫,設計用來在 C# 中建立、處理和轉換 PDF 檔案。 它被廣泛用於 從 HTML、CSS、JavaScript 及其他格式產生高品質的 PDF。 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.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 時,請記得將 "YOUR_API_KEY" 替換為 API 金鑰。 結論 本教學探討如何使用 C# 中的 HttpClient 類來傳送 HTTP 請求並處理回應。 我們還介紹了 IronPDF,這是一個功能強大的函式庫,用於在 .NET 應用程式中產生 PDF。 我們示範了如何結合這些技術,使用 HttpClient 從網頁服務擷取 HTML 內容,並使用 IronPDF 將其轉換為 PDF。 IronPdf 提供免費試用,其授權價格從 $799 開始,對於尋求全面 PDF 生成功能的開發人員而言,這是一款非常有價值的工具。 常見問題解答 如何在 C# 中將 HTML 內容轉換為 PDF? 您可以利用 IronPDF 將 HTML 內容轉換為 PDF,方法包括 RenderHtmlAsPdf 等。這可讓您輕鬆地將包含 CSS 和 JavaScript 的 HTML 字串轉換成專業的 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 類。將 Proxy 屬性設定為 WebProxy 範例,並在建立 HttpClient 範例時啟用 UseProxy 選項。 Jacob Mellor 立即與工程團隊聊天 首席技術長 Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。 相關文章 更新2025年12月11日 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多 更新2025年12月20日 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 閱讀更多 C# AES Encryption (How It Works For Developers)C# Discriminated Union (How It Work...
更新2025年12月11日 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 閱讀更多
更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多
更新2025年12月20日 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 閱讀更多