的libcurl - PUT发行后POST [英] libcurl - POST after PUT issue
问题描述
我使用C中的libcurl编写一个HTTP客户端。然而,重新使用相同的句柄传递一个 PUT
后跟一个开机自检时,我面临着一个奇怪的问题
。下面的示例code:
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;
}
问题是,而不是发送一个 PUT
则 POST
,它会发送2 PUT
取值:
The problem is that, instead sending a PUT
then a POST
, it sends 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
A PUT后
或 POST <前/ code>。只能用
PUT出现该问题
后跟一个 POST
。
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?
推荐答案
如果你发出一个POST请求,然后想使一个头部或使用相同的再利用处理GET,必须使用显式地设置新的请求类型CURLOPT_NOBODY或CURLOPT_HTTPGET或相似。
"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."
编辑:它实际上是比这更简单。你需要这样的通话之间重置选项:
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);
}
这篇关于的libcurl - PUT发行后POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!