user180574
user180574

Reputation: 6094

libcurl: write call back function not invoked

I am using libcurl to send a POST request, and am trying to get response using the callback function. Below is the relevant code.

main ()
{
    ...
    curl_global_init(CURL_GLOBAL_ALL);
    CURL *curl = curl_easy_init ();
    curl_easy_setopt(curl, CURLOPT_URL, url_string);
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    if (strlen(query_string) > 0)
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, query_string);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &write_buffer);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCB);
    CURLcode res = curl_easy_perform(curl);
    if (CURLE_OK == res)
        printf("response: %s\n", write_buffer.data);
    else
        printf("curl failed\n");
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    ...
}

struct BufferType
{ 
    Str data;
    BufferType() {};
    size_t Append(char *src, size_t size, size_t nmemb)
    {
        data.Append(Str(src, size * nmemb));
        return size * nmemb;
    }
};

size_t WriteCB(char *data, size_t size, size_t nmemb, BufferType *buffer)
{
    printf("WriteCB: %s\n", data);
    fflush(stdout);
    return buffer->Append(data, size, nmemb);
}

When I launched the program, I can see it is executed (the server responds with "200 OK"). But the program just hangs there, here is the output:

WriteCB: HTTP/1.1 100 Continue

WriteCB: 

More info: if I use GET method for other URL, and change the two lines related to POST to

curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);

Then the code works fine.

What could be wrong?

Upvotes: 1

Views: 2128

Answers (2)

jzapata
jzapata

Reputation: 1229

Glad you found the issue. I originally though you might not be using POST correctly with libcurl which is easy to do. So, I tried your code but didn't find any issue with it.

So, it had to be either an issue with the how you were setting it up or the server itself. The callbacks were behaving as expected. I wanted to try it out because I generally use POST with libcurl like this:

struct curl_httppost* post = NULL;
struct curl_httppost* last = NULL;

curl_formadd(&post, &last, ..., CURLFORM_END);

Here is an example

Upvotes: 0

user180574
user180574

Reputation: 6094

SOLVED

In the command line, I let the user to specify query string, and I have a statement such that if the "query_string" is empty then do not call "curl_easy_setopt(curl, CURLOPT_POSTFIELDS, query_string);".

Setting curl to verbose shows that the request header has "Expect: 100-continue". So I guess it is because the query string is not set yet. Even it is empty, it should be set.

Upvotes: 1

Related Questions