我正在使用 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;
}
问题是,它发送了 2 个 PUT
,而不是先发送一个 PUT
,然后发送一个 POST
:
> 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()
)。如果我在 PUT
之后或 POST
之前发送 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);
}
关于c - libcurl - PUT 问题后的 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8410869/