.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);
    }
}
Imports System
Imports System.Net.Http
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		Dim client = New HttpClient() 'HttpClient client
		Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London") ' HTTP response for GET request
		Dim responseBody = Await response.Content.ReadAsStringAsync() ' response content
		Console.WriteLine(responseBody)
	End Function
End Class
VB   C#

在此範例中:

  • 使用 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);
}
Dim client = New HttpClient()
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Paris")
If response.IsSuccessStatusCode Then
	Dim responseBody = Await response.Content.ReadAsStringAsync()
	Console.WriteLine(responseBody)
End If
VB   C#
  • 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);
}
Dim client = New HttpClient()
Dim requestBody = New StringContent("{ ""location"": ""New York"" }", Encoding.UTF8, "application/json")
Dim response = Await client.PostAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody)
If response.IsSuccessStatusCode Then
	Dim responseBody = Await response.Content.ReadAsStringAsync()
	Console.WriteLine(responseBody)
End If
VB   C#
  • 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);
}
Dim client = New HttpClient()
Dim requestBody = New StringContent("{ ""location"": ""Tokyo"", ""days"": 3 }", Encoding.UTF8, "application/json")
Dim response = Await client.PutAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody)
If response.IsSuccessStatusCode Then
	Dim responseBody = Await response.Content.ReadAsStringAsync()
	Console.WriteLine(responseBody)
End If
VB   C#
  • 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");
}
Dim client = New HttpClient()
Dim response = Await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY")
If response.IsSuccessStatusCode Then
	Console.WriteLine("Resource deleted successfully")
End If
VB   C#
  • 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}");
}
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Sydney")
If response.IsSuccessStatusCode Then
	Dim responseBody = Await response.Content.ReadAsStringAsync()
	Console.WriteLine(responseBody)
Else
	Console.WriteLine($"Error: {response.StatusCode}")
End If
VB   C#
  • 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;
}
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
VB   C#

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

使用 HttpClient 與相依性注入

在網路應用程式中,建議的方法是將 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
VB   C#

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

連接池和代理設置

透過重複使用 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);
Dim handler = New HttpClientHandler With {
	.Proxy = New WebProxy("http://proxyserver:port"),
	.UseProxy = True
}
Dim client = New HttpClient(handler)
VB   C#

錯誤處理和狀態碼

若要處理不同的 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}");
    }
}
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")
		' Response Status Code Cases
		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
VB   C#

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; }
}
Imports System.Net.Http
Imports System.Text.Json
Imports System.Threading.Tasks
Private client = New HttpClient()
Private response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London")
Private jsonString = await response.Content.ReadAsStringAsync()
Private weatherResponse = JsonSerializer.Deserialize(Of WeatherResponse)(jsonString)
Public Class WeatherResponse
	Public Property Location() As String
	Public Property Temperature() As Double
End Class
VB   C#

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}");
        }
    }
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Imports System.Text.Json
Imports IronPdf
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		License.LicenseKey = "IRONSUITE.WINSWRITERSIRONSOFTWARECOM.31102-3E7C9B3308-CIHWVP2-L2A7FVEBUSFN-DP6CI32YVXIN-45HQSAZOBOCW-YCYETGS4ENQX-NZXXG4YCPAYI-EBCIJ43PNLJW-DKWC7U-TFXPQ4LKLXGPEA-DEPLOYMENT.TRIAL-G43TTA.TRIAL.EXPIRES.20.MAY.2025"
		Dim client = New HttpClient()
		Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/forecast.json?key=55c9040a6ad34c6c90470702240609&q=London&days=3")
		If response.IsSuccessStatusCode Then
			Dim jsonContent = Await response.Content.ReadAsStringAsync()
			' Pretty-print the JSON
			Dim jsonElement = JsonSerializer.Deserialize(Of JsonElement)(jsonContent)
			Dim formattedJson = JsonSerializer.Serialize(jsonElement, New JsonSerializerOptions With {.WriteIndented = True})
			' Escape the JSON for HTML
			formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson)
			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>"
			Dim renderer = New ChromePdfRenderer()
			Dim 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}")
		End If
	End Function
End Class
VB   C#

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 生成功能的開發人員來說是非常有價值的工具。

< 上一頁
C# AES 加密(開發者如何使用)
下一個 >
C# 判別聯合(它如何為開發者工作)

準備開始了嗎? 版本: 2024.12 剛剛發布

免費 NuGet 下載 總下載次數: 11,622,374 查看許可證 >