我正在使用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
。
有谁知道为什么会这样?
答案 0 :(得分:1)
“如果您发出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);
}