IRONSOFTWAREHOME
開發者更新

C# HttpClient (如何為開發人員運作)

Jacob Mellor,首席技術官 @ Team Iron
Jacob Mellor
Updated: 2026年4月21日

The HttpClient class, part of the .NET framework, provides methods to send HTTP requests and receive HTTP responses from a resource identified by a URI. 它簡化了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);
    }
}

在此範例中:

  • 使用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);
        }
    }
}
  • 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);
        }
    }
}
  • 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);
        }
    }
}
  • 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");
        }
    }
}
  • 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}");
        }
    }
}
  • Response.StatusCode提供狀態程式碼(例如,200,404)。
  • ReadAsStringAsync()異步讀取。

高效使用HttpClient

HttpClient實例應重用,以利用連接池功能並避免耗盡系統資源。 通常的模式是在應用程式或服務的整個生命週期中建立一個HttpClient實例。這可以使用靜態變數或依賴注入來為網頁應用程式完成。

靜態HttpClient範例

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

您還可以建立命名客戶端和型別化客戶端進行更具體的配置。

連接池和代理設置

通過重用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);

錯誤處理和狀態程式碼

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

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

ReadAsStringAsync()方法簡化了直接將JSON內容讀取到C#物件中。

介紹IronPDF

C# HttpClient (如何為開發人員提供服務):圖1 - IronPDF

IronPDF是一個.NET的PDF程式庫,專為建立、操作和轉換C#中的PDF文件而設計。 它廣泛用於從HTML、CSS、JavaScript和其他格式生成高質量的PDF。 IronPDF提供了HTML到PDF轉換、PDF合併、水印,甚至高級操作如數位簽名和PDF加密等功能。 它相容各種平台,包括Windows、Linux和macOS,使其成為跨平台開發的多功能解決方案。

將IronPDF與HttpClient搭配使用

在C#中結合IronPDF和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}");
        }
    }
}
C#

C# HttpClient (如何為開發人員提供服務):圖2 - PDF輸出

請記得在使用真實的天氣API時將"YOUR_API_KEY"替換為API金鑰。

結論

本教程探討了在C#中使用HttpClient類發送HTTP請求和處理響應。 我們還介紹了IronPDF,它是一個用於在.NET應用程式中生成PDF的強大程式庫。 我們演示瞭如何通過HttpClient從網路服務檢索HTML內容,並使用IronPDF將其轉化為PDF來結合這些技術。

IronPDF提供免費試用,其授權$999起售,使其成為尋求全面PDF生成功能的開發者的寶貴工具。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰。

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

OR
bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
預訂您的免費現場演示
Booking Badge

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密。
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰。
無需信用卡或帳戶建立
C# 用於PDF的NuGet程式庫
使用NuGet安裝

版本: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解決方案資源管理器,右鍵點選參考,管理NuGet包
  2. 選擇瀏覽並搜尋"IronPdf"
  3. 選擇套件並安裝
C# PDF DLL
下載DLL

版本: 2026.9

或者點擊此處下載Windows安裝程式。

  1. 下載並解壓IronPDF到類似~/Libs的位置,位於您的解決方案目錄中
  2. 在Visual Studio解決方案資源管理器,右鍵點選參考。選擇瀏覽,"IronPdf.dll"

授權從$999起