简体   繁体   中英

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

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:

在此处输入图像描述

Why is this happening? How do I fix this?

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM