CMouse
CMouse

Reputation: 130

HTTP POST with LibCurl

Sending POST request using libcurl C++. I have tried almost all combination except the right one which I could not figure out.

curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE);  /*Not Recommended to use but since certificates are not available this is a workaround added*/
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, FALSE);  /*Not Recommended to use but since certificates are not available this is a workaround added*/

curl_easy_setopt(curl, CURLOPT_HTTPPOST, TRUE);  //CURLOPT_POST does not work as well
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, sJson);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, bytesCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, bytesCallback);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &headBuffer);

sJson is a std::string which has the body that is created by pb2json.

I cannot figure out why the body is not sent ? Is there some API i am missing if libcurl, any lead is appreciated !

Upvotes: 3

Views: 4540

Answers (1)

CocoCrisp
CocoCrisp

Reputation: 815

I would prefer using custom request here CURLOPT_CUSTOMREQUEST below is the code snippet that works fine! When you use custom requests nothing implies and you have to explicitly define the CURLOPT_HTTPHEADER

Use a list here, for brevity I have used the minimal code here.

Also when you pass sJson pass it as a c type string using c_str() and remember to use +1 while passing the content length (which I somehow missed initially) as in C, strings are just char arrays which, by convention, end with a NULL byte.

struct curl_slist* slist = NULL;
slist = curl_slist_append(slist, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);

curl_easy_setopt(curl, CURLOPT_POSTFIELDS, sJson.c_str()); /* data goes here */
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, sJson.length() + 1); /* data goes here */

EDIT: Use of curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); might create problems in redirection, use it according to your use case.

Upvotes: 5

Related Questions