Faust Faust - 3 months ago 31
C++ Question

Curl post null object

I used example code from curl's help, but server receives empty objects and null custom header. GET method works fine.

strbuf.GetString()
- it's json object which converted to String.

CURL *curl;
CURLcode res;
struct WriteThis pooh;
res = curl_global_init(CURL_GLOBAL_DEFAULT);
struct curl_slist *headers=NULL;
curl_slist_append(headers, "Accept: application/json");
curl_slist_append( headers, "Content-Type: application/json");
curl_slist_append( headers, "charsets: utf-8");
curl_slist_append( headers, "AuthToken: 9BA1B05482567E64037573FFB68672DCB52E4993");
curl = curl_easy_init();
if (curl)
{
pooh.readptr = strbuf.GetString();
pooh.sizeleft = (long)strlen(strbuf.GetString());
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
curl_easy_setopt(curl, CURLOPT_READDATA, &pooh);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,writer);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, &pooh);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, pooh.sizeleft);
res = curl_easy_perform(curl);
if (CURLE_OK == res)
{
char *ct;
res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
if((CURLE_OK == res) && ct){

}
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();

struct WriteThis {
const char *readptr;
long sizeleft;
};

static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp)
{
struct WriteThis *pooh = (struct WriteThis *)userp;

if(size*nmemb < 1)
return 0;

if(pooh->sizeleft) {
*(char *)ptr = pooh->readptr[0]; /* copy one single byte */
pooh->readptr++; /* advance pointer */
pooh->sizeleft--; /* less data left */
return 1; /* we return 1 byte at a time! */
}

return 0; /* no more data left to deliver */
}

Answer

Instead:

struct curl_slist *headers=NULL; 
curl_slist_append(headers, "Accept: application/json");  
curl_slist_append( headers, "Content-Type: application/json");
curl_slist_append( headers, "charsets: utf-8"); 
curl_slist_append( headers, "AuthToken: 9BA1B05482567E64037573FFB68672DCB52E4993"); 
curl = curl_easy_init();

This:

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, "charsets: utf-8"); 
    headers=curl_slist_append( headers, "AuthToken: 9BA1B05482567E64037573FFB68672DCB52E4993"); 
    curl = curl_easy_init();
Comments