C# HttpClient(開発者向けの仕組み)
このHttpClientクラスは、.NET Frameworkの一部で、URI によって識別されるリソースから HTTP リクエストを送信し、HTTP レスポンスを受信する手段を提供します。 これは、GET、POST、PUT、DELETE リクエストのいずれかを実行している場合でも、HTTP リクエストの呼び出しを簡素化します。 このガイドでは、実用的なシナリオでの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);
}
}Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Module Program
Async Function Main(args As String()) As Task
Using client As 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 Using
End Function
End ModuleImports System
Imports System.Net.Http
Imports System.Threading.Tasks
Module Program
Async Function Main(args As String()) As Task
Using client As 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 Using
End Function
End Moduleこの例では:
- 新しいHttpClientインスタンスは
var client = new HttpClient()を使用して作成されます。 - HTTP GETリクエストは
GetAsyncメソッドを使用して送信されます。 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 ClassImports 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 ClassIsSuccessStatusCodeプロパティはリクエストが成功したことを保証します。- 応答本体は
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 ClassImports 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 ClassrequestBody)でリクエストを送信します。- コンテンツタイプを指定する必要があります(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 ClassImports 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 ClassPutAsyncは指定されたURIでリソースを更新するためのPUTリクエストを送信します。- リクエストボディには通常、更新されるデータが含まれています。
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 ClassImports 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 ClassDeleteAsyncはリソースを削除するための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 ClassImports 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 ClassResponse.StatusCodeはステータスコード(例: 200, 404)を提供します。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;
}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 ModulePublic 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 ModuleHttpClient インスタンスはアプリケーション全体で再利用され、新しい HTTP 接続の作成に費やされるオーバーヘッドを減少させます。
依存性注入を使用したHttpClientの使用
Web アプリケーションでは、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 SubPublic 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)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 FunctionImports 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 FunctionJSON レスポンスボディの取り扱い
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
Module Example
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 Module
Public Class WeatherResponse
Public Property Location As String
Public Property Temperature As Double
End ClassImports System
Imports System.Net.Http
Imports System.Text.Json
Imports System.Threading.Tasks
Module Example
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 Module
Public Class WeatherResponse
Public Property Location As String
Public Property Temperature As Double
End ClassReadAsStringAsync()メソッドは、JSONコンテンツを直接C#オブジェクトに読み込むことを簡略化します。
IronPDFの紹介
C# HttpClient (開発者向けの動作): 図1 - IronPDF
IronPDF は、C#で PDF ファイルを作成、操作、および変換するために設計された .NET PDF ライブラリです。 これは、HTML、CSS、JavaScript、およびその他の形式から高品質のPDFを生成するために広く使用されています。 IronPDFは、HTMLからPDFへの変換、PDFのマージ、透かし付け、さらにはデジタル署名やPDF暗号化のような高度な操作などの機能を提供します。 Windows、Linux、macOSなどのさまざまなプラットフォームと互換性があり、クロスプラットフォーム開発において多用途のソリューションとなっています。
IronPDFとHttpClientの使用
IronPDFをC#のHttpClientクラスと組み合わせることで、WebリソースからPDFドキュメントを動的に生成および操作する効果的な方法となります。 たとえば、HttpClientを介してURLからHTMLコンテンツを取得し、このHTMLをIronPDFでPDFドキュメントに変換できます。 これは、ライブWebコンテンツに基づいてレポート、請求書、または任意のドキュメントを動的に生成する場合に便利です。
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 = 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 ModuleImports 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 = 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 ModuleC# HttpClient (開発者向けの動作): 図2 - PDFの出力
実際の天気 API を使用する際には、"YOUR_API_KEY"をAPIキーに置き換えることを忘れないでください。
結論
C# HttpClient (開発者向けの動作): 図3 - ライセンス
このチュートリアルでは、C# で HttpClient クラスを使用して HTTP リクエストを送信し、レスポンスを処理する方法を探りました。 また、.NET アプリケーションでの PDF 生成に強力なライブラリである IronPDF を紹介しました。 私たちは、HttpClientを使用してWebサービスからHTMLコンテンツを取得し、それをIronPDFを使用してPDFに変換することで、これらの技術を統合する方法を示しました。
IronPDFは無料トライアルを提供しており、そのライセンスは$999から始まります。開発者が包括的なPDF生成能力を求める際の価値あるツールです。
ジェイコブ・メラーはIron Softwareの最高技術責任者(CTO)であり、C# PDFテクノロジーを開拓する先見的なエンジニアです。Iron Softwareのコアコードベースを支えるオリジナル開発者として、彼は創業以来、会社の製品アーキテクチャを形成し、CEOのCameron Rimingtonとともに、会社をNASA、Tesla、および世界的な政府機関にサービスを提供する50人以上の会社に変えました。1999年にロンドンで最初のソフトウェアビジネスを開業し、2005年に最初 for .NETコンポーネントを作成した後、Microsoftのエコシステム全体で複雑な問題を解決することを専門としました。