Language/C# WPF

C#에서 HTTP와 HTTPS 요청 처리하기: HttpClient 사용 예제

멱군 2024. 8. 21. 10:34

C#에서 웹 요청을 처리할 때, HTTP와 HTTPS 요청을 모두 처리해야 할 경우가 종종 있습니다. 이를 위해 HttpClient 클래스를 사용하여 손쉽게 HTTP와 HTTPS 요청을 보낼 수 있습니다. 이 글에서는 C#에서 HttpClient를 사용하여 HTTP 및 HTTPS 요청을 처리하는 방법과 SSL 인증서 검증 비활성화 방법에 대해 알아보겠습니다.

 

 

서버보안으로 HTTP에서 HTTPS로 변경

최근 서버 보안 문제가 발생하여 모든 HTTP 통신을 HTTPS로 변경해야 했습니다. 하지만 변경 후 일부 통신이 원활하지 않았고, 그로 인해 HTTP와 HTTPS 요청을 모두 처리할 수 있는 방법을 찾게 되었습니다.

 

1. HttpClient 인스턴스 생성

먼저, HTTP와 HTTPS 요청을 보내기 위해 HttpClient 인스턴스를 생성합니다. 아래 코드는 HttpClient를 사용하여 HTTP 및 HTTPS 요청을 보내는 예제입니다.

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

public class Program
{
    private static readonly HttpClient client = new HttpClient();

    public static async Task Main(string[] args)
    {
        await SendHttpRequest();
        await SendHttpsRequest();
    }

    private static async Task SendHttpRequest()
    {
        try
        {
            string url = "http://A.mydomain.com/api/endpoint";
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"HTTP Response: {responseBody}");
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"HTTP Request Exception: {e.Message}");
        }
    }

    private static async Task SendHttpsRequest()
    {
        try
        {
            string url = "https://A.mydomain.com/api/endpoint";
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"HTTPS Response: {responseBody}");
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"HTTPS Request Exception: {e.Message}");
        }
    }
}

 

2. SSL 인증서 검증 비활성화 (테스트용)

HTTPS 요청에서 SSL 인증서 검증 문제로 인해 요청이 실패하는 경우, SSL 인증서 검증을 비활성화하여 테스트할 수 있습니다. 그러나 이 방법은 보안상 좋지 않기 때문에 실제 운영 환경에서는 사용하지 않는 것이 좋습니다.

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

public class Program
{
    private static readonly HttpClientHandler handler = new HttpClientHandler
    {
        ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
    };

    private static readonly HttpClient client = new HttpClient(handler);

    public static async Task Main(string[] args)
    {
        await SendHttpRequest();
        await SendHttpsRequest();
    }

    private static async Task SendHttpRequest()
    {
        try
        {
            string url = "http://A.mydomain.com/api/endpoint";
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"HTTP Response: {responseBody}");
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"HTTP Request Exception: {e.Message}");
        }
    }

    private static async Task SendHttpsRequest()
    {
        try
        {
            string url = "https://A.mydomain.com/api/endpoint";
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"HTTPS Response: {responseBody}");
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"HTTPS Request Exception: {e.Message}");
        }
    }
}

SSL을 비활성화 하는 구문은 "ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true"을 참고 하시면 됩니다.

위의 예제를 통해 C#에서 HTTP와 HTTPS 요청을 모두 처리할 수 있습니다. 필요한 경우 SSL 인증서를 올바르게 설정하여 보안성을 유지할 수 있습니다.