libcurl - POST after PUT issue

2019-08-13 18:31发布

问题:

I'm writing a http client in C using libcurl. However, I'm facing a weird issue when re-using the same handle for transfer a PUT followed by a POST. A sample code below:

#include <curl/curl.h>

void send_a_put(CURL *handle){
    curl_easy_setopt(handle, CURLOPT_UPLOAD, 1L); //PUT
    curl_easy_setopt(handle, CURLOPT_INFILESIZE, 0L);
    curl_easy_perform(handle);        
}

void send_a_post(CURL *handle){
    curl_easy_setopt(handle, CURLOPT_POST, 1L);  //POST
    curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE, 0L);         
    curl_easy_perform(handle);        
}

int main(void){
    CURL *handle = curl_easy_init();

    curl_easy_setopt(handle, CURLOPT_URL, "http://localhost:8888/");
    curl_easy_setopt(handle, CURLOPT_HTTPHEADER, 
                     curl_slist_append(NULL, "Expect:"));

    curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L); //for debug 

    send_a_put(handle);
    send_a_post(handle);

    curl_easy_cleanup(handle);
    return 0;
}

The problem is that, instead sending a PUT then a POST, it sends 2 PUTs:

> PUT / HTTP/1.1
Host: localhost:8888
Accept: */*
Content-Length: 0

< HTTP/1.1 200 OK
< Date: Wed, 07 Dec 2011 04:47:05 GMT
< Server: Apache/2.0.63 (Unix) PHP/5.3.2 DAV/2
< Content-Length: 0
< Content-Type: text/html

> PUT / HTTP/1.1
Host: localhost:8888
Accept: */*
Content-Length: 0

< HTTP/1.1 200 OK
< Date: Wed, 07 Dec 2011 04:47:05 GMT
< Server: Apache/2.0.63 (Unix) PHP/5.3.2 DAV/2
< Content-Length: 0
< Content-Type: text/html

Changing the order makes both transfers occur correctly (i.e send_a_post() then send_a_put()). Everything goes fine also if I send a GET after a PUT or before a POST. The problem occurs only with a PUT followed by a POST.

Does anyone know why it happens?

回答1:

"If you issue a POST request and then want to make a HEAD or GET using the same re-used handle, you must explicitly set the new request type using CURLOPT_NOBODY or CURLOPT_HTTPGET or similar."

From the documentation

EDIT: it's actually even simpler than this. you need to reset your options between calls like this:

void
send_a_put (CURL * handle)
{
  curl_easy_setopt (handle, CURLOPT_POST, 0L);    // disable POST
  curl_easy_setopt (handle, CURLOPT_UPLOAD, 1L);  // enable PUT
  curl_easy_setopt (handle, CURLOPT_INFILESIZE, 0L);
  curl_easy_perform (handle);
}

void
send_a_post (CURL * handle)
{
  curl_easy_setopt (handle, CURLOPT_UPLOAD, 0L);  // disable PUT
  curl_easy_setopt (handle, CURLOPT_POST, 1L);    // enable POST
  curl_easy_setopt (handle, CURLOPT_POSTFIELDSIZE, 0L);
  curl_easy_perform (handle);
}