반응형
Visual Studio C++에서 libcurl로 JSON 요청/응답 처리하기
C++ 프로젝트에서 외부 REST API 서버와 통신할 때는 보통 JSON을 이용합니다.
이때 가장 널리 사용되는 라이브러리가 libcurl
입니다.
이번 글에서는 Visual Studio 환경에서 libcurl을 활용해 JSON 요청을 보내고 응답을 처리하는 방법을 단계별로 설명합니다.
STEP 1. libcurl 설치하기
- vcpkg 사용:
vcpkg install curl
실행 후 자동으로 프로젝트와 연동됩니다. - 수동 설치:
- libcurl 공식 다운로드 페이지에서 Windows용 패키지 다운로드
- Visual Studio 프로젝트 속성 → 추가 포함 디렉터리, 추가 라이브러리 디렉터리 등록
- 링커 → 추가 종속성에
libcurl.lib
추가
STEP 2. JSON 요청/응답 처리 함수 작성
#include <iostream>
#include <string>
#include <curl/curl.h>
using namespace std;
// 응답 콜백
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
((string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
// JSON 요청 함수
bool ExecCurlRequest(const string& url, string& response,
const string& method = "GET", const string& body = "")
{
CURL* curl = curl_easy_init();
if (!curl) return false;
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Accept: application/json");
if (method == "POST" || method == "PUT")
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
if (!body.empty())
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
if (method != "GET" && method != "POST")
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method.c_str());
CURLcode res = curl_easy_perform(curl);
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
return (res == CURLE_OK && http_code == 200);
}
STEP 3. API 요청 실행 예제
int main() {
curl_global_init(CURL_GLOBAL_DEFAULT);
string response;
// GET 요청
if (ExecCurlRequest("https://jsonplaceholder.typicode.com/posts/1", response, "GET"))
cout << "GET 응답: " << response << endl;
// POST 요청
string jsonBody = R"({"title":"foo","body":"bar","userId":1})";
if (ExecCurlRequest("https://jsonplaceholder.typicode.com/posts", response, "POST", jsonBody))
cout << "POST 응답: " << response << endl;
curl_global_cleanup();
return 0;
}
STEP 4. JSON 응답 파싱하기
응답은 문자열로 전달되므로, JSON을 다루려면 별도의 파서 라이브러리가 필요합니다. 가장 많이 쓰이는 라이브러리는 nlohmann/json
입니다.
#include <nlohmann/json.hpp>
using json = nlohmann::json;
json j = json::parse(response);
cout << "id 값: " << j["id"] << endl;
STEP 5. 테스트용 API 서버 (jsonplaceholder)
위 코드 예제에서 사용한 https://jsonplaceholder.typicode.com
은 무료 JSON API 테스트 서버입니다.
회원가입이나 인증 없이 누구나 사용할 수 있으며, REST API 학습이나 HTTP 요청 테스트에 자주 활용됩니다.
주요 엔드포인트 예시:
GET /posts/1
→ 게시글 하나 조회POST /posts
→ 새 게시글 등록 (응답에 가짜 id 반환)GET /users
→ 사용자 목록 조회GET /comments
→ 댓글 목록 조회
예를 들어 GET https://jsonplaceholder.typicode.com/posts/1
요청을 보내면 아래와 같은 JSON 응답을 받을 수 있습니다:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati",
"body": "quia et suscipit..."
}
이처럼 jsonplaceholder
는 실제 데이터베이스가 연결된 것은 아니지만, JSON 응답 형식이 잘 갖춰져 있어서 libcurl 코드 테스트와 JSON 파싱 연습에 매우 유용합니다.
정리
- Visual Studio에
libcurl
을 설치한다. - 헤더를
Accept: application/json
,Content-Type: application/json
으로 설정한다. - 응답을 문자열로 받은 뒤 JSON 라이브러리로 파싱한다.
이 과정을 통해 로그인, 데이터 전송, 외부 서버 연동 등 다양한 기능을 쉽게 구현할 수 있습니다.
반응형
'c++' 카테고리의 다른 글
Visual Studio C++ SendMessage 사용법 정리 (0) | 2025.09.18 |
---|---|
Visual Studio C++ PostMessage 사용법 정리 (0) | 2025.09.18 |
[C++] 메모리누수와 해결방안 (0) | 2025.03.24 |
[C++] 메모리 누수 (1) | 2025.03.09 |
[c++] cmake 작성법 (0) | 2024.07.03 |