푸터 콘텐츠로 바로가기
.NET 도움말

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);
    }
}
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
$vbLabelText   $csharpLabel

이 예시에서는 다음과 같습니다.

  • 새로운 HttpClient 인스턴스는 var client = new HttpClient()를 사용하여 생성됩니다.
  • HTTP GET 요청은 GetAsync 메서드를 사용하여 전송됩니다.
  • HttpResponseMessagevar 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
$vbLabelText   $csharpLabel
  • 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
$vbLabelText   $csharpLabel
  • PostAsync는 지정된 본문 (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
$vbLabelText   $csharpLabel
  • PutAsync는 지정된 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 Class
$vbLabelText   $csharpLabel
  • 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
$vbLabelText   $csharpLabel
  • 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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

특정 설정을 위해 명명된 클라이언트 및 유형화된 클라이언트를 만드는 것도 가능합니다.

연결 풀링 및 프록시 설정

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)
$vbLabelText   $csharpLabel

오류 처리 및 상태 코드

다른 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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

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}");
        }
    }
}
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

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		License.LicenseKey = "YOUR_LICENSE_KEY" ' Set your IronPDF license key
		Dim client = 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 Function
End Class
$vbLabelText   $csharpLabel

C# HttpClient (개발자를 위한 작동 방식): 그림 2 - PDF 출력

실제 날씨 API를 사용할 때 "YOUR_API_KEY"를 API 키로 교체하는 것을 잊지 마세요.

결론

C# HttpClient (개발자를 위한 작동 방식): 그림 3 - 라이선스

이 튜토리얼에서는 C#에서 HttpClient 클래스를 사용하여 HTTP 요청을 보내고 응답을 처리하는 방법을 탐색했습니다. 우리는 또한 .NET 애플리케이션에서 PDF를 생성하기 위한 강력한 라이브러리인 IronPDF를 소개했습니다. 이 기술들을 결합하여 HttpClient를 사용해 웹 서비스에서 HTML 콘텐츠를 가져와 IronPDF로 이를 PDF로 변환하는 방법을 보여주었습니다.

IronPDF는 무료 체험판을 제공하며, $799부터 시작하는 라이선스를 제공합니다. 이는 포괄적인 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# 객체로 변환할 수 있습니다.

C#에서 HTTP 상태 코드를 처리하는 모범 사례는 무엇인가요?

C#에서는 HttpResponseMessageStatusCode 속성을 체크하여 HTTP 상태 코드를 처리합니다. 조건문을 사용하여 HttpStatusCode.OKHttpStatusCode.NotFound와 같은 특정 코드를 관리하여 적절한 오류 처리를 구현합니다.

IronPDF가 PDF 기능으로 .NET 애플리케이션을 어떻게 향상시키나요?

IronPDF는 PDF 파일을 생성, 조작, 변환하기 위한 강력한 도구를 제공함으로써 .NET 애플리케이션을 향상시킵니다. HTML, CSS 및 JavaScript에서 고품질의 PDF 생성을 지원하여 개발자가 동적 문서를 쉽게 작성할 수 있습니다.

HttpClient를 사용하여 PDF 변환을 위한 HTML 콘텐츠를 가져올 수 있나요?

예, HttpClient는 웹 리소스에서 HTML 콘텐츠를 가져올 수 있으며, 이 콘텐츠는 IronPDF를 사용하여 PDF로 변환될 수 있습니다. 이 방법은 실시간 웹 데이터나 동적 콘텐츠로부터 PDF를 생성하기에 적합합니다.

C#에서 HttpClient의 프록시 설정을 어떻게 구성하나요?

HttpClient의 프록시 설정을 구성하려면 HttpClientHandler 클래스를 사용할 수 있습니다. WebProxy 인스턴스로 Proxy 속성을 설정하고 HttpClient 인스턴스를 생성할 때 UseProxy 옵션을 활성화하세요.

제이콥 멜러, 팀 아이언 최고기술책임자
최고기술책임자

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

제이콥은 맨체스터 대학교에서 토목공학 학사 학위(BEng)를 최우등으로 취득했습니다(1998~2001). 1999년 런던에서 첫 소프트웨어 회사를 설립하고 2005년 첫 .NET 컴포넌트를 개발한 후, 마이크로소프트 생태계 전반에 걸쳐 복잡한 문제를 해결하는 데 전문성을 발휘해 왔습니다.

그의 대표 제품인 IronPDF 및 Iron Suite .NET 라이브러리는 전 세계적으로 3천만 건 이상의 NuGet 설치 수를 기록했으며, 그의 핵심 코드는 전 세계 개발자들이 사용하는 다양한 도구에 지속적으로 활용되고 있습니다. 25년의 실무 경험과 41년의 코딩 전문성을 바탕으로, 제이콥은 차세대 기술 리더들을 양성하는 동시에 기업 수준의 C#, Java, Python PDF 기술 혁신을 주도하는 데 주력하고 있습니다.

아이언 서포트 팀

저희는 주 5일, 24시간 온라인으로 운영합니다.
채팅
이메일
전화해