본문 바로가기
📁 [4] 개발자 정보 & 코드 노트/C#

C# Windows Forms 강의 71편: 비동기 네트워크 통신 - HTTP 요청 및 응답 처리

by wawManager 2025. 4. 14.

 

1. 강의 개요

이번 강의에서는 HttpClient를 사용해 비동기 네트워크 요청을 처리하는 방법을 배웁니다.
RESTful API를 호출하여 데이터를 가져오거나 서버에 데이터를 전송하는 기능을 구현하며,
UI를 통해 요청 및 응답 데이터를 확인할 수 있는 간단한 HTTP 클라이언트 애플리케이션을 만들어봅니다.


2. 학습 목표

  • HttpClient를 사용한 GET/POST 요청 구현
  • 비동기 요청 처리로 UI 응답성 유지
  • JSON 응답 데이터를 파싱하여 DataGridView에 표시
  • POST 요청으로 데이터를 서버에 전송

3. 기능 요구사항

필수 기능

1️⃣ GET 요청:

  • RESTful API로 데이터를 요청하고 결과를 JSON 형식으로 표시

2️⃣ POST 요청:

  • 사용자가 입력한 데이터를 API에 POST 방식으로 전송

3️⃣ JSON 데이터 표시:

  • GET 요청의 응답 데이터를 DataGridView에 표시

4️⃣ UI 응답성 유지:

  • 비동기 요청 처리로 요청 중에도 UI 작업 가능

4. 실습: 비동기 HTTP 클라이언트 제작

1️⃣ 폼 구성

  • 폼(Form) 이름: Form1
  • 컨트롤 배치

컨트롤 타입 이름 위치 크기

TextBox txtApiUrl 폼 상단 왼쪽 (300 x 30)
Button btnSendGet 폼 상단 중앙 (100 x 30)
DataGridView dgvData 폼 중앙 (500 x 300)
TextBox txtPostData 폼 하단 왼쪽 (300 x 60)
Button btnSendPost 폼 하단 오른쪽 (100 x 60)

📌 폼 디자인 예시:

--------------------------------------------------
| [API URL: TextBox]        [Send GET 버튼]       |
--------------------------------------------------
|          [DataGridView - JSON 데이터 표시]       |
--------------------------------------------------
| [POST 데이터: TextBox]         [Send POST 버튼] |
--------------------------------------------------

2️⃣ 코드 작성

(1) HttpClient를 사용한 GET 요청

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp_HttpClient
{
    public partial class Form1 : Form
    {
        private readonly HttpClient _httpClient;

        public Form1()
        {
            InitializeComponent();
            _httpClient = new HttpClient(); // HttpClient 초기화
        }

        // GET 요청 처리
        private async void btnSendGet_Click(object sender, EventArgs e)
        {
            string apiUrl = txtApiUrl.Text.Trim();

            if (string.IsNullOrEmpty(apiUrl))
            {
                MessageBox.Show("API URL을 입력하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                string jsonResponse = await _httpClient.GetStringAsync(apiUrl); // GET 요청

                // JSON 응답 데이터 파싱
                var data = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(jsonResponse);

                // DataGridView에 데이터 바인딩
                dgvData.DataSource = data;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"GET 요청 실패: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

(2) HttpClient를 사용한 POST 요청

        // POST 요청 처리
        private async void btnSendPost_Click(object sender, EventArgs e)
        {
            string apiUrl = txtApiUrl.Text.Trim();
            string postData = txtPostData.Text.Trim();

            if (string.IsNullOrEmpty(apiUrl) || string.IsNullOrEmpty(postData))
            {
                MessageBox.Show("API URL과 POST 데이터를 입력하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                var content = new StringContent(postData, System.Text.Encoding.UTF8, "application/json"); // JSON 형식으로 데이터 변환
                HttpResponseMessage response = await _httpClient.PostAsync(apiUrl, content); // POST 요청

                response.EnsureSuccessStatusCode(); // 요청 성공 여부 확인

                string responseData = await response.Content.ReadAsStringAsync(); // 응답 데이터 읽기
                MessageBox.Show($"POST 요청 성공: {responseData}", "성공", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"POST 요청 실패: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

(3) Designer 코드

        private void InitializeComponent()
        {
            this.txtApiUrl = new TextBox();
            this.btnSendGet = new Button();
            this.dgvData = new DataGridView();
            this.txtPostData = new TextBox();
            this.btnSendPost = new Button();

            // API URL TextBox 설정
            this.txtApiUrl.Location = new System.Drawing.Point(10, 10);
            this.txtApiUrl.Size = new System.Drawing.Size(300, 30);

            // Send GET Button 설정
            this.btnSendGet.Location = new System.Drawing.Point(320, 10);
            this.btnSendGet.Size = new System.Drawing.Size(100, 30);
            this.btnSendGet.Text = "Send GET";
            this.btnSendGet.Click += new EventHandler(this.btnSendGet_Click);

            // DataGridView 설정
            this.dgvData.Location = new System.Drawing.Point(10, 50);
            this.dgvData.Size = new System.Drawing.Size(500, 300);

            // POST 데이터 TextBox 설정
            this.txtPostData.Location = new System.Drawing.Point(10, 360);
            this.txtPostData.Size = new System.Drawing.Size(300, 60);
            this.txtPostData.Multiline = true;

            // Send POST Button 설정
            this.btnSendPost.Location = new System.Drawing.Point(320, 360);
            this.btnSendPost.Size = new System.Drawing.Size(100, 60);
            this.btnSendPost.Text = "Send POST";
            this.btnSendPost.Click += new EventHandler(this.btnSendPost_Click);

            // Form 설정
            this.ClientSize = new System.Drawing.Size(520, 450);
            this.Controls.Add(this.txtApiUrl);
            this.Controls.Add(this.btnSendGet);
            this.Controls.Add(this.dgvData);
            this.Controls.Add(this.txtPostData);
            this.Controls.Add(this.btnSendPost);
            this.Text = "HTTP 클라이언트 애플리케이션";
        }

3️⃣ 실행 결과

1️⃣ GET 요청

  • API URL 입력 후 "Send GET" 클릭 → JSON 응답 데이터를 DataGridView에 표시

2️⃣ POST 요청

  • API URL과 POST 데이터 입력 후 "Send POST" 클릭 → 서버로 데이터 전송 및 응답 확인

3️⃣ UI 응답성 유지

  • 요청 중에도 다른 UI 작업 가능

5. 주요 개념 요약

  • HttpClient: HTTP 요청 및 응답 처리를 위한 클래스
  • async/await: 비동기 작업 구현을 위한 키워드
  • JSON 데이터 파싱: System.Text.Json을 사용한 JSON 직렬화/역직렬화
  • StringContent: POST 요청 데이터 변환

 

📌 #CSharp #WindowsForms #HttpClient #RESTfulAPI #GET요청 #POST요청 #JSON파싱