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

2024. 8. 21. 10:34· Language/C# WPF
목차
  1. 서버보안으로 HTTP에서 HTTPS로 변경
  2. 1. HttpClient 인스턴스 생성
  3. 2. SSL 인증서 검증 비활성화 (테스트용)

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 요청을 보내는 예제입니다.

csharpusing 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 인증서 검증을 비활성화하여 테스트할 수 있습니다. 그러나 이 방법은 보안상 좋지 않기 때문에 실제 운영 환경에서는 사용하지 않는 것이 좋습니다.

csharpusing 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 인증서를 올바르게 설정하여 보안성을 유지할 수 있습니다.

저작자표시 비영리 동일조건 (새창열림)

'Language > C# WPF' 카테고리의 다른 글

WPF 'Path'은(는) 'System.Windows.Shapes.Path' 및 'System.IO.Path' 사이에 모호한 참조입니다 오류 해결 방법  (0) 2024.07.12
WPF에서 'System.Windows' 네임스페이스에 'Forms' 형식 또는 네임스페이스 이름이 없습니다 오류 해결 방법  (0) 2024.07.12
WPF 프로그램 시작 경로 알아내는 방법 3가지  (0) 2024.02.07
[WPF] BitmapImage로 이미지 파일(image file load) 읽기  (0) 2024.02.07
[C#] .net 혼합모드 어셈블리 런타임의 버젼 오류 해결 및 app.config 추가방법  (0) 2023.12.05
  1. 서버보안으로 HTTP에서 HTTPS로 변경
  2. 1. HttpClient 인스턴스 생성
  3. 2. SSL 인증서 검증 비활성화 (테스트용)
'Language/C# WPF' 카테고리의 다른 글
  • WPF 'Path'은(는) 'System.Windows.Shapes.Path' 및 'System.IO.Path' 사이에 모호한 참조입니다 오류 해결 방법
  • WPF에서 'System.Windows' 네임스페이스에 'Forms' 형식 또는 네임스페이스 이름이 없습니다 오류 해결 방법
  • WPF 프로그램 시작 경로 알아내는 방법 3가지
  • [WPF] BitmapImage로 이미지 파일(image file load) 읽기


멱군
멱군
IT 업계에서 개발자로 일하고 있습니다. 다양한 프로그래밍 언어의 코드 문제 해결과 IT 최신 트렌드를 다룹니다. Python부터 Java까지, 초보자와 전문가 모두에게 필요한 정보를 제공하며, IT 분야의 심층적인 논의와 분석을 통해 지식을 넓힐 수 있는 공간입니다.
멱군
멱군! 프로그래밍을 하자.
멱군
  • ROOT (252)
    • SERVER_CLOUD (12)
    • 끄적끄적 (72)
      • AI 잡담 (26)
      • 블로그이야기 (28)
      • 음주코딩 (1)
      • 운영체제 (17)
    • TOOLS (10)
    • Language (148)
      • SQL (32)
      • HTML (1)
      • CSS (6)
      • JAVASCRIPT (11)
      • Nodejs (21)
      • JSP (2)
      • C# WPF (23)
      • Flutter (15)
      • Python (2)
      • UNITY (5)
      • Arduino (9)
      • Kinect (2)
      • Android IOS SmartTV (8)
      • Computer Vision Computer.. (1)
      • C C++ MFC (7)
      • etc (3)
    • 알고리즘 (3)
    • Project (6)
    • 포트폴리오 (1)
      • Project (0)
      • Publication (0)
      • My Paper (0)

공지사항

전체
오늘
어제
hELLO · Designed By 정상우.v4.2.2
멱군
C#에서 HTTP와 HTTPS 요청 처리하기: HttpClient 사용 예제
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.