C# HttpClient (如何為開發人員運作)
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);
}
}
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);
}
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient() ' Create a new instance of HttpClient
' Send a GET request to the specified URI and store the HTTP response
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London")
' Retrieve the response content as a string
Dim responseBody = Await response.Content.ReadAsStringAsync()
' Print the response content to the console
Console.WriteLine(responseBody)
End Function
End Class
在此範例中:
- 使用
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);
}
}
}
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);
}
}
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Friend Class Example
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient()
Dim 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 Then
Dim responseBody = Await response.Content.ReadAsStringAsync()
Console.WriteLine(responseBody)
End If
End Function
End Class
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);
}
}
}
Imports System
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Friend Class Example
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient()
Dim requestBody = New StringContent("{ ""location"": ""New York"" }", Encoding.UTF8, "application/json")
' Send the POST request with the specified body
Dim 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 Then
Dim responseBody = Await response.Content.ReadAsStringAsync()
Console.WriteLine(responseBody)
End If
End Function
End Class
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);
}
}
}
Imports System
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Friend Class Example
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient()
Dim requestBody = New StringContent("{ ""location"": ""Tokyo"", ""days"": 3 }", Encoding.UTF8, "application/json")
' Send a PUT request to update the resource
Dim 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 Then
Dim responseBody = Await response.Content.ReadAsStringAsync()
Console.WriteLine(responseBody)
End If
End Function
End Class
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");
}
}
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Friend Class Example
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient()
' Send a DELETE request to remove the resource
Dim response = Await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY")
' Check if the request was successful
If response.IsSuccessStatusCode Then
Console.WriteLine("Resource deleted successfully")
End If
End Function
End Class
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}");
}
}
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Friend Class Example
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient()
Dim 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 Then
Dim responseBody = Await response.Content.ReadAsStringAsync()
Console.WriteLine(responseBody)
Else
Console.WriteLine($"Error: {response.StatusCode}")
End If
End Function
End Class
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;
}
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
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
您還可以建立命名客戶端和型別化客戶端進行更具體的配置。
連接池和代理設置
通過重用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);
Imports System.Net
Imports System.Net.Http
Private handler = New HttpClientHandler With {
.Proxy = New WebProxy("http://proxyserver:port"),
.UseProxy = True
}
Private 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}");
}
}
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}");
}
}
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")
' Handle the response based on the status code
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
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; }
}
Imports System
Imports System.Net.Http
Imports System.Text.Json
Imports System.Threading.Tasks
Friend Class Example
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient()
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London")
Dim jsonString = Await response.Content.ReadAsStringAsync()
' Deserialize the JSON response into a WeatherResponse object
Dim weatherResponse = JsonSerializer.Deserialize(Of WeatherResponse)(jsonString)
Console.WriteLine($"Location: {weatherResponse.Location}, Temperature: {weatherResponse.Temperature}")
End Function
End Class
Public Class WeatherResponse
Public Property Location() As String
Public Property Temperature() As Double
End Class
ReadAsStringAsync()方法簡化了直接將JSON內容讀取到C#物件中。
介紹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}");
}
}
}
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}");
}
}
}
Imports System
Imports System.Net.Http
Imports System.Text.Json
Imports System.Threading.Tasks
Imports IronPdf
Module Program
Async Function Main(args As String()) As Task
License.LicenseKey = "YOUR_LICENSE_KEY" ' Set your IronPDF license key
Using client As New HttpClient()
Dim 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 Then
Dim jsonContent = Await response.Content.ReadAsStringAsync()
Dim jsonElement = JsonSerializer.Deserialize(Of JsonElement)(jsonContent)
' Format the JSON content for pretty-printing
Dim formattedJson = JsonSerializer.Serialize(jsonElement, New JsonSerializerOptions With {.WriteIndented = True})
' Escape the JSON for HTML
formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson)
' Create an HTML string for PDF generation
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>"
' Generate the PDF from the HTML content
Dim renderer As New ChromePdfRenderer()
Dim 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}")
End If
End Using
End Function
End Module

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

本教程探討了在C#中使用HttpClient類發送HTTP請求和處理響應。 我們還介紹了IronPDF,它是一個用於在.NET應用程式中生成PDF的強大程式庫。 我們演示瞭如何通過HttpClient從網路服務檢索HTML內容,並使用IronPDF將其轉化為PDF來結合這些技術。
IronPDF提供免費試用,其授權$999起售,使其成為尋求全面PDF生成功能的開發者的寶貴工具。
常見問題
如何在C#中將HTML內容轉換為PDF?
您可以使用IronPDF來通過它的方法例如RenderHtmlAsPdf將HTML內容轉換為PDF。這使您能夠輕鬆地將包含CSS和JavaScript的HTML字串轉換為專業的PDF文件。
如何在C#中結合HttpClient與PDF生成?
通過整合HttpClient與IronPDF,您可以從網路資源中檢索HTML內容,然後使用IronPDF的轉換方法將其轉換為PDF文件。這對於從即時資料中建立報告或發票特別有用。
重用HttpClient實例的重要性是什麼?
重用HttpClient實例對於資源管理效率至關重要。它利用了連接池,從而最大限度地減少了每次請求建立新連接的開銷,提高了應用程式的性能。
如何在C#中反序列化JSON回應?
在C#中,可以使用JsonSerializer類來反序列化JSON回應。在將回應內容獲取為字串後,您可以使用JsonSerializer.Deserialize將其轉換為強型別的C#物件。
處理HTTP狀態碼的最佳實踐是什麼?
在C#中處理HTTP狀態碼涉及檢查HttpResponseMessage的StatusCode屬性。使用條件語句來管理特定程式碼,例如HttpStatusCode.OK或HttpStatusCode.NotFound,以實現適當的錯誤處理。
IronPDF如何通過PDF功能增強.NET應用程式?
IronPDF通過提供強大的工具用於建立、操作和轉換PDF文件來增強.NET應用程式。它支持從HTML、CSS和JavaScript生成高質量的PDF,為開發人員提供輕鬆生成動態文件的能力。
我可以使用HttpClient來獲取要轉換為PDF的HTML內容嗎?
可以,HttpClient可以從網路資源中獲取HTML內容,然後使用IronPDF將其轉換為PDF。這種方法非常適合從即時網頁資料或動態內容中生成PDF。
如何為C#中的HttpClient配置代理設置?
要為HttpClient配置代理設置,您可以使用HttpClientHandler類。將Proxy屬性設置為一個WebProxy實例,並且在建立HttpClient實例時啟用UseProxy選項。




