libcurl - PUT问题后的POST

时间:2011-12-07 05:36:38

标签: c http post libcurl

我正在使用libcurl在C中编写一个http客户端。但是,当重新使用相同的句柄转移PUT后跟POST时,我遇到了一个奇怪的问题。以下示例代码:

#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;
}

问题在于,发送PUT然后发送POST,它会发送2 PUT s:

> 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

更改顺序会使两次传输都正确进行(即send_a_post()然后send_a_put())。如果我在GET之后或PUT之前发送POST,一切都会顺利进行。仅在PUT后跟POST

时才会出现此问题

有谁知道为什么会这样?

1 个答案:

答案 0 :(得分:1)

“如果您发出POST请求,然后想要使用相同的重用句柄进行HEAD或GET,则必须使用CURLOPT_NOBODY或CURLOPT_HTTPGET或类似方法显式设置新请求类型。”

来自the documentation

编辑:它实际上甚至比这更简单。您需要在以下呼叫之间重置选项:

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);
}