You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中使用libcurl执行指定HTTP请求并获取JSON格式的服务器响应

Implementing HTTP Requests with libcurl in C++

Got it, let's build a clean, easy-to-use wrapper around libcurl that matches the syntax you're looking for (like curl.get(url)), and convert each of your curl commands into working C++ code. We'll handle headers, request bodies, and capture the JSON response from the server.

Prerequisites

  • Make sure you have libcurl installed on your system (package like libcurl4-openssl-dev on Debian/Ubuntu, or via vcpkg on Windows).
  • When compiling, link against libcurl with the -lcurl flag (e.g., g++ your_code.cpp -o your_program -lcurl).
  • Include these headers in your code:
    #include <curl/curl.h>
    #include <string>
    #include <vector>
    #include <stdexcept>
    

Step 1: Response Callback Function

Libcurl uses a callback to capture the server's response. We'll define this helper function first:

size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* s) {
    size_t newLength = size * nmemb;
    try {
        s->append((char*)contents, newLength);
    } catch(std::bad_alloc &e) {
        // Handle memory allocation failure
        return 0;
    }
    return newLength;
}

Step 2: Curl Wrapper Class

To get the clean syntax you want, let's wrap libcurl in a simple class. This will handle common setup, headers, and request types:

class CurlWrapper {
private:
    CURL* curl;
    struct curl_slist* headers = nullptr;

    void init() {
        curl_global_init(CURL_GLOBAL_ALL);
        curl = curl_easy_init();
        if(!curl) {
            throw std::runtime_error("Failed to initialize curl");
        }
        // Set common headers (Accept and Content-Type)
        addHeader("Accept: application/json");
        addHeader("Content-Type: application/json");
    }

    void addHeader(const std::string& header) {
        headers = curl_slist_append(headers, header.c_str());
    }

public:
    CurlWrapper(const std::string& bearerToken) {
        init();
        addHeader("Authorization: Bearer " + bearerToken);
    }

    ~CurlWrapper() {
        if(headers) curl_slist_free_all(headers);
        if(curl) curl_easy_cleanup(curl);
        curl_global_cleanup();
    }

    std::string get(const std::string& url) {
        std::string response;
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        CURLcode res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            throw std::runtime_error("GET request failed: " + std::string(curl_easy_strerror(res)));
        }
        return response;
    }

    std::string put(const std::string& url, const std::string& payload) {
        std::string response;
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        CURLcode res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            throw std::runtime_error("PUT request failed: " + std::string(curl_easy_strerror(res)));
        }
        return response;
    }

    std::string post(const std::string& url, const std::string& payload) {
        std::string response;
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        CURLcode res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            throw std::runtime_error("POST request failed: " + std::string(curl_easy_strerror(res)));
        }
        return response;
    }

    std::string del(const std::string& url) {
        std::string response;
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        CURLcode res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            throw std::runtime_error("DELETE request failed: " + std::string(curl_easy_strerror(res)));
        }
        return response;
    }
};

Step 3: Implement Your Specific Requests

Now let's use this wrapper to replicate each of your curl commands:

GET Request

int main() {
    try {
        CurlWrapper curl("apikey"); // Replace with your actual API key
        std::string response = curl.get("https://pterodactyl.file.properties/api/client/account");
        // response contains the JSON from the server
        std::cout << "GET Response:\n" << response << std::endl;
    } catch(const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}

PUT Request

int main() {
    try {
        CurlWrapper curl("apikey");
        std::string payload = R"({"email": "example@xample.com", "password": "Password"})";
        std::string response = curl.put("https://pterodactyl.file.properties/api/client/account/email", payload);
        std::cout << "PUT Response:\n" << response << std::endl;
    } catch(const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}

POST Request

int main() {
    try {
        CurlWrapper curl("apikey");
        std::string payload = R"({"description": "Restricted IPs", "allowed_ips": ["127.0.0.1", "192.168.0.1"]})";
        std::string response = curl.post("https://pterodactyl.file.properties/api/client/account/api-keys", payload);
        std::cout << "POST Response:\n" << response << std::endl;
    } catch(const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}

DELETE Request

int main() {
    try {
        CurlWrapper curl("apikey");
        std::string response = curl.del("https://pterodactyl.file.properties/api/client/account/api-keys/NWKMYMT2Mrav0Iq2");
        std::cout << "DELETE Response:\n" << response << std::endl;
    } catch(const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}

Notes

  • The R"()" syntax is a C++ raw string literal, which makes writing JSON payloads easier (no need to escape quotes).
  • To parse the JSON response, you can use a header-only library like nlohmann/json for straightforward handling.
  • Always handle exceptions to catch curl initialization or request failures gracefully.

内容的提问来源于stack exchange,提问作者Leopold95

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:52:37