다양한 언어 스크립트 예제

#include <iostream>
#include <curl/curl.h>

// 응답 데이터 처리를 위한 콜백 함수
int write_callback(char* data, size_t size, size_t nmemb, std::string* buffer) {
    int result = 0;
    if (buffer != nullptr) {
        buffer->append(data, size * nmemb);
        result = size * nmemb;
    }
    return result;
}

int main() {
    // libcurl 초기화
    curl_global_init(CURL_GLOBAL_DEFAULT);

    // 요청 URL 설정
    std::string url = "http://example.com/post";

    // JSON 데이터 준비
    std::string json = "{\"name\": \"John\", \"age\": 30}";

    // POST 요청 보내기
    CURL* curl = curl_easy_init();
    if (curl) {
        // 요청 헤더 설정
        struct curl_slist* headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");

        // 요청 옵션 설정
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

        // 요청 실행
        CURLcode res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            std::cout << "Failed to send POST request: " << curl_easy_strerror(res) << std::endl;
        }

        // 응답 결과 가져오기
        long http_code = 0;
        curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);

        std::string response_data;
        curl_easy_getinfo(curl, CURLINFO_PRIVATE, &response_data);

        // 요청 응답 결과 출력
        std::cout << "HTTP Status Code: " << http_code << std::endl;
        std::cout << "Response Data: " << response_data << std::endl;

        // 리소스 해제
        curl_easy_cleanup(curl);
    }

    // libcurl 정리
    curl_global_cleanup();

    return 0;
}