libcurl – PUT问题后的POST

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

 #include  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

 > 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  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() )。 如果我在PUTPOST之前发送GET ,一切都会好起来的。 只有PUT后跟POST才会出现问题。

有谁知道它为什么会发生?

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

从文档中

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

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