.NET 幫助

C# HttpClient(開發人員如何使用)

里根普恩
里根普恩
2024年10月23日
分享:

HttpClient 类.NET 框架的一部分,提供了從由 URI 識別的資源發送 HTTP 請求和接收 HTTP 響應的方法。 它簡化了 HTTP 請求的發送,無論是執行 GET、POST 請求、PUT 還是 DELETE 請求。 本指南將涵蓋 HttpClient 在實際場景中的基本使用,以及介紹IronPDF 庫.

建立新的 HttpClient 實例

HttpClient 類別用於發送 HTTP 請求。 您可以如下創建其新實例:

using System;
using System.Net.Http;
class Program
{
    static async Task Main(string[] args)
    {
        using var client = new HttpClient(); //HttpClient client
        var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London"); // HTTP response for GET request
        var responseBody = await response.Content.ReadAsStringAsync(); // response content
        Console.WriteLine(responseBody);
    }
}
using System;
using System.Net.Http;
class Program
{
    static async Task Main(string[] args)
    {
        using var client = new HttpClient(); //HttpClient client
        var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London"); // HTTP response for GET request
        var responseBody = await response.Content.ReadAsStringAsync(); // response content
        Console.WriteLine(responseBody);
    }
}

在此範例中:

  • 使用 var client = new HttpClient 創建一個新的 HttpClient 實例().
  • 使用 GetAsync 方法發送 HTTP GET 請求。
  • HttpResponseMessage 存儲在變數 response 中。
  • 使用 response.Content.ReadAsStringAsync 來獲取響應的內容。().

發送 HTTP 請求

HTTP GET 請求

要發送 HTTP GET 請求並處理回應:

var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Paris");
if (response.IsSuccessStatusCode)
{
    var responseBody = await response.Content.ReadAsStringAsync();
    Console.WriteLine(responseBody);
}
var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Paris");
if (response.IsSuccessStatusCode)
{
    var responseBody = await response.Content.ReadAsStringAsync();
    Console.WriteLine(responseBody);
}
  • IsSuccessStatusCode 屬性確保請求成功。
  • 使用 ReadAsStringAsync 非同步讀取回應正文。

HTTP POST 請求

發送 POST 請求涉及添加請求主體:

var client = new HttpClient();
var requestBody = new StringContent("{ \"location\": \"New York\" }", Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);
if (response.IsSuccessStatusCode)
{
    var responseBody = await response.Content.ReadAsStringAsync();
    Console.WriteLine(responseBody);
}
var client = new HttpClient();
var requestBody = new StringContent("{ \"location\": \"New York\" }", Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);
if (response.IsSuccessStatusCode)
{
    var responseBody = await response.Content.ReadAsStringAsync();
    Console.WriteLine(responseBody);
}
  • PostAsync 發送具有指定主體的請求(请求体).
  • 您必須指定內容類型(application/JSON).

HTTP PUT 請求

HTTP PUT 請求更新資源:

var client = new HttpClient();
var requestBody = new StringContent("{ \"location\": \"Tokyo\", \"days\": 3 }", Encoding.UTF8, "application/json");
var response = await client.PutAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);
if (response.IsSuccessStatusCode)
{
    var responseBody = await response.Content.ReadAsStringAsync();
    Console.WriteLine(responseBody);
}
var client = new HttpClient();
var requestBody = new StringContent("{ \"location\": \"Tokyo\", \"days\": 3 }", Encoding.UTF8, "application/json");
var response = await client.PutAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);
if (response.IsSuccessStatusCode)
{
    var responseBody = await response.Content.ReadAsStringAsync();
    Console.WriteLine(responseBody);
}
  • PutAsync 發送一個 PUT 請求來更新指定 URI 上的資源。
  • 請求主體通常包含需要更新的數據。

HTTP DELETE 請求

發送 HTTP DELETE 請求:

var client = new HttpClient();
var response = await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY");
if (response.IsSuccessStatusCode)
{
    Console.WriteLine("Resource deleted successfully");
}
var client = new HttpClient();
var response = await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY");
if (response.IsSuccessStatusCode)
{
    Console.WriteLine("Resource deleted successfully");
}
  • DeleteAsync 發送一個 DELETE 請求以移除該資源。

處理 HTTP 回應

每個 HTTP 請求會返回一個 HttpResponseMessage 物件,其中包含響應正文、標頭和狀態碼。 例如:

var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Sydney");
if (response.IsSuccessStatusCode)
{
    var responseBody = await response.Content.ReadAsStringAsync();
    Console.WriteLine(responseBody);
}
else
{
    Console.WriteLine($"Error: {response.StatusCode}");
}
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Sydney");
if (response.IsSuccessStatusCode)
{
    var responseBody = await response.Content.ReadAsStringAsync();
    Console.WriteLine(responseBody);
}
else
{
    Console.WriteLine($"Error: {response.StatusCode}");
}
  • Response.StatusCode 提供狀態代碼(例如,200,404).
  • response.Content 包含響應主體,可使用 ReadAsStringAsync 異步讀取。

高效使用HttpClient

應重複使用 HttpClient 實例以利用連線池並避免耗盡系統資源。 一個典型的模式是為您的應用程序或服務的整個生命週期創建單一的 HttpClient 實例。這可以通過使用靜態變量或依賴注入來為網路應用程序實現。

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

HttpClient實例在整個應用程式中重複使用,以減少建立新HTTP連接的開銷。

使用 HttpClient 與相依性注入

在網路應用程式中,建議的方法是將 HttpClient 註冊為單例服務:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient();
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient();
}

您還可以創建具名客戶端和類型化客戶端,以進行更具體的配置。

連接池和代理設置

透過重複使用 HttpClient 實例,您可以受益於連接池,這將提升對同一伺服器的多重請求效能。 您也可以使用 HttpClientHandler 類別來配置代理設定:

var handler = new HttpClientHandler
{
    Proxy = new WebProxy("http://proxyserver:port"),
    UseProxy = true
};
var client = new HttpClient(handler);
var handler = new HttpClientHandler
{
    Proxy = new WebProxy("http://proxyserver:port"),
    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");
        // Response Status Code Cases
        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");
        // Response Status Code Cases
        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.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
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();
var weatherResponse = JsonSerializer.Deserialize<WeatherResponse>(jsonString);
public class WeatherResponse
{
    public string Location { get; set; }
    public double Temperature { get; set; }
}
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
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();
var weatherResponse = JsonSerializer.Deserialize<WeatherResponse>(jsonString);
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 生成高品質的 PDF、CSS、JavaScript 及其他格式。 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.Threading.Tasks;
using System.Text.Json;
using IronPdf;
class Program
{
    static async Task Main(string[] args)
    {
        License.LicenseKey = "IRONSUITE.WINSWRITERSIRONSOFTWARECOM.31102-3E7C9B3308-CIHWVP2-L2A7FVEBUSFN-DP6CI32YVXIN-45HQSAZOBOCW-YCYETGS4ENQX-NZXXG4YCPAYI-EBCIJ43PNLJW-DKWC7U-TFXPQ4LKLXGPEA-DEPLOYMENT.TRIAL-G43TTA.TRIAL.EXPIRES.20.MAY.2025";
        using var client = new HttpClient();
        var response = await client.GetAsync("https://api.weatherapi.com/v1/forecast.json?key=55c9040a6ad34c6c90470702240609&q=London&days=3");
        if (response.IsSuccessStatusCode)
        {
            var jsonContent = await response.Content.ReadAsStringAsync();
            // Pretty-print the JSON
            var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonContent);
            var formattedJson = JsonSerializer.Serialize(jsonElement, new JsonSerializerOptions { WriteIndented = true });
            // Escape the JSON for HTML
            formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson);
            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>";
            var renderer = new ChromePdfRenderer();
            var pdf = renderer.RenderHtmlAsPdf(htmlContent);
            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.Threading.Tasks;
using System.Text.Json;
using IronPdf;
class Program
{
    static async Task Main(string[] args)
    {
        License.LicenseKey = "IRONSUITE.WINSWRITERSIRONSOFTWARECOM.31102-3E7C9B3308-CIHWVP2-L2A7FVEBUSFN-DP6CI32YVXIN-45HQSAZOBOCW-YCYETGS4ENQX-NZXXG4YCPAYI-EBCIJ43PNLJW-DKWC7U-TFXPQ4LKLXGPEA-DEPLOYMENT.TRIAL-G43TTA.TRIAL.EXPIRES.20.MAY.2025";
        using var client = new HttpClient();
        var response = await client.GetAsync("https://api.weatherapi.com/v1/forecast.json?key=55c9040a6ad34c6c90470702240609&q=London&days=3");
        if (response.IsSuccessStatusCode)
        {
            var jsonContent = await response.Content.ReadAsStringAsync();
            // Pretty-print the JSON
            var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonContent);
            var formattedJson = JsonSerializer.Serialize(jsonElement, new JsonSerializerOptions { WriteIndented = true });
            // Escape the JSON for HTML
            formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson);
            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>";
            var renderer = new ChromePdfRenderer();
            var pdf = renderer.RenderHtmlAsPdf(htmlContent);
            pdf.SaveAs("F://weather_report.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        else
        {
            Console.WriteLine($"Failed to retrieve content. Status code: {response.StatusCode}");
        }
    }
}

C# HttpClient(對開發人員的工作原理):圖 2 - PDF 輸出

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

結論

C# HttpClient(開發人員的工作原理):圖 3 - 授權

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

IronPDF 提供免費試用,其授權起價為 $749,使其成為尋求全面 PDF 生成能力的開發人員的有價值工具。

里根普恩
軟體工程師
Regan 畢業於雷丁大學,擁有電子工程學士學位。在加入 Iron Software 之前,他的工作角色讓他專注於單一任務;而他在 Iron Software 工作中最喜歡的是他所能承擔的工作範圍,無論是增加銷售價值、技術支持、產品開發或市場營銷。他喜歡了解開發人員如何使用 Iron Software 庫,並利用這些知識不斷改進文檔和開發產品。
< 上一頁
C# AES 加密(開發者如何使用)
下一個 >
C# 判別聯合(它如何為開發者工作)