Ví dụ tập lệnh đa ngôn ngữ

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

// Hàm gọi lại, dùng để xử lý dữ liệu phản hồi
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() {
    // Khởi tạo libcurl
    curl_global_init(CURL_GLOBAL_DEFAULT);

    // Thiết lập URL yêu cầu
    std::string url = "http://example.com/post";

    // Chuẩn bị dữ liệu JSON
    std::string json = "{\"name\": \"John\", \"age\": 30}";

    // Gửi yêu cầu POST
    CURL* curl = curl_easy_init();
    if (curl) {
        // Thiết lập tiêu đề yêu cầu
        struct curl_slist* headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");

        // Thiết lập các tùy chọn yêu cầu
        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);

        // Thực thi yêu cầu
        CURLcode res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            std::cout << "Failed to send POST request: " << curl_easy_strerror(res) << std::endl;
        }

        // Lấy kết quả phản hồi
        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);

        // Xuất kết quả phản hồi của yêu cầu
        std::cout << "HTTP Status Code: " << http_code << std::endl;
        std::cout << "Response Data: " << response_data << std::endl;

        // Giải phóng tài nguyên
        curl_easy_cleanup(curl);
    }

    // Dọn dẹp libcurl
    curl_global_cleanup();

    return 0;
}