Thursday, September 1, 2022

[SOLVED] Not able to send a JSON request using libcurl in C++

Issue

I am trying to access a GraphQL server with C++ and I am using the libcurl library to make the HTTP Post request.

I got started with libcurl after reading the docs and I was testing the requests that were created using a test endpoint at hookbin.com

Here is the sample code:

int main(int argc, char* argv[]) {
    CURL* handle = curl_easy_init();
    curl_easy_setopt(handle, CURLOPT_URL, "https://hookb.in/YVk7VyoEyesQjy0QmdDl");

    struct curl_slist* headers = NULL;
    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/json");
    headers = curl_slist_append(headers, "charset: utf-8");
    curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers);

    string data = "{\"hi\" : \"there\"}";

    cout << data << endl;
    curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data);

    CURLcode success = curl_easy_perform(handle);
    return 0;
}

When I send this post request I expect the request body to be the json {"hi": "there"} but I get some weird nonsense in the body. Here is what the request body looks like:

enter image description here

Why is this happening? How do I fix this?


Solution

curl_easy_setopt is a C function and can't deal with std::string data and CURLOPT_POSTFIELDS expects char* postdata. Call std::string::c_str() for getting char*.

curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data.c_str());


Answered By - 273K
Answer Checked By - Robin (WPSolving Admin)