pythonc++chttplibcurl

How to pass string to REST API using libcurl in cpp


I want to send string to my rest API call in c++. So, I am using libcurl library.

CURL *curl;
CURLcode res;

curl = curl_easy_init();
if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:5000/sample");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"hi\" : \"there\"}");
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);

    std::cout << res << std::endl;
}

O/P from flask API is,

ImmutableMultiDict([('{"hi" : "there"}', '')])

the above code is working:

I am getting the sent result in my python Flask application.

but,

string body = "{\"hi\" : \"there\"}";
CURL *curl;
CURLcode res;

curl = curl_easy_init();
if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "localhost:5000/sample");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body);
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);

    std::cout << res << std::endl;
}

O/P from flask API is:

ImmutableMultiDict([('��-ؿ\x7f', '')])

this code is not working. the only difference is i am assigning the string to a variable and passing that to curl.

I am wondering why it's working? how to pass variable to curl?


Solution

  • curl_easy_setopt(curl, CURLOPT_POSTFIELDS, ...); expects a char* as it's parameter, which you give in the first example but not in the second. Try curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str()); instead.

    In C++ string literals have type char* (not actually true, but close enough for now) which is a legacy from C. The string type is different. Use string::c_str() if you have a C++ string but need to call a function which requires a legacy C string.