跳過到頁腳內容
.NET幫助

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

HttpClient 類別是.NET Framework的一部分,它提供了從 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);
    }
}
$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簡介

C# HttpClient(開發者使用方法):圖 1 - IronPDF

IronPDF是一個.NET PDF 函式庫,旨在以 C# 建立、操作和轉換 PDF 檔案。 它廣泛用於從 HTML、CSS、 JavaScript和其他格式產生高品質的 PDF 。 IronPDF提供 HTML 轉 PDF、PDF 合併、浮水印等功能,甚至提供數位簽章和 PDF 加密等進階操作。 它相容於多種平台,包括 Windows、Linux 和 macOS,使其成為跨平台開發的多功能解決方案。

將IronPDF與 HttpClient 結合使用

將IronPDF與 C# 中的 HttpClient 類別結合使用,是動態地從 Web 資源產生和操作 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

C# HttpClient(開發者使用方法):圖 2 - PDF 輸出

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

結論

C# HttpClient(開發者使用方法):圖 3 - 授權

本教學探討如何使用 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 狀態碼涉及檢查 HttpResponseMessageStatusCode 屬性。使用條件語句來管理特定的狀態碼,例如 HttpStatusCode.OKHttpStatusCode.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 選項。

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

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me