
C# HttpClient (개발자를 위한 작동 방식)
.NET Framework 일부인 HttpClient 클래스는 HTTP 요청을 보내고 URI로 식별된 리소스로부터 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 Module이 예시에서는 다음과 같습니다.
- 새로운 HttpClient 인스턴스가
var client = new HttpClient()를 사용하여 생성됩니다. - HTTP GET 요청이
GetAsync메소드를 사용하여 전송됩니다. 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);
}
}
}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 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);
}
}
}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 ClassPostAsync은(는) 지정된 본문(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);
}
}
}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 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");
}
}
}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 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}");
}
}
}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 ClassResponse.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 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 사용
웹 애플리케이션에서 권장하는 접근 방식은 HttpClient를 싱글턴 서비스로 등록하는 것입니다:
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);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}");
}
}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 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; }
}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 Class이 ReadAsStringAsync() 메소드는 JSON 내용을 C# 객체로 직접 읽는 것을 간소화합니다.
IronPDF 소개합니다
C# HttpClient (개발자를 위해 작동하는 방법): 그림 1 - IronPDF
IronPDF는 C#에서 PDF 파일을 생성, 조작 및 변환하도록 설계된 .NET PDF 라이브러리입니다. HTML에서 고품질 PDF를 생성하는 것, CSS, JavaScript 및 기타 형식을 위해 널리 사용됩니다. IronPDF는 HTML을 PDF로 변환, PDF 합치기, 워터마킹 및 심지어 디지털 서명 및 PDF 암호화와 같은 고급 작업을 포함한 기능을 제공합니다. Windows, Linux 및 macOS를 포함한 다양한 플랫폼과 호환 가능하여 플랫폼 간 개발에 대한 유연한 솔루션을 제공합니다.
IronPDF와 함께 HttpClient 사용하기
IronPDF와 C#의 HttpClient 클래스를 결합하면 웹 리소스로부터 PDF 문서를 동적으로 생성 및 조작하는 효과적인 방법입니다. 예를 들어, HttpClient를 통해 URL에서 HTML 콘텐츠를 가져오고 이를 IronPDF를 사용하여 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}");
}
}
}
C# HttpClient (개발자를 위해 작동하는 방법): 그림 2 - PDF 출력
실제 날씨 API를 사용할 때 "YOUR_API_KEY"를 API 키로 교체하는 것을 잊지 마세요.
결론
C# HttpClient (개발자를 위해 작동하는 방법): 그림 3 - 라이선싱
이 튜토리얼에서는 C#에서 HttpClient 클래스를 사용하여 HTTP 요청을 보내고 응답을 처리하는 방법을 탐색했습니다. 우리는 또한 .NET 애플리케이션에서 PDF를 생성하기 위한 강력한 라이브러리인 IronPDF를 소개했습니다. 이 기술들을 결합하여 HttpClient를 사용해 웹 서비스에서 HTML 콘텐츠를 가져와 IronPDF로 이를 PDF로 변환하는 방법을 보여주었습니다.
IronPDF는 무료 체험판을 제공하며, $999에서 라이선스가 시작되어 포괄적인 PDF 생성 기능을 찾는 개발자에게 가치 있는 도구입니다.

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.
관련 기사


