2011-12-07 8 views
1

libcurlを使用してCでhttpクライアントを作成しています。しかし、同じハンドルを再使用してPUTに転送し、次にPOSTを転送すると、奇妙な問題に直面しています。以下のサンプルコード:libcurl - 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; 
} 

問題ではなく、その後PUTPOSTを送信し、それが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())。 PUTの後に、またはPOSTの前にGETを送信しても、すべてうまく行きます。この問題はPUTとそれに続くPOSTでのみ発生します。

なぜそれが起こるのか知っていますか?

答えて

1

"POSTリクエストを発行し、同じ再使用ハンドルを使用してHEADまたはGETを作成する場合は、CURLOPT_NOBODYまたはCURLOPT_HTTPGETなどを使用して明示的に新しいリクエストタイプを設定する必要があります。

the documentationからEDIT:それは実際にはこれよりもさらに簡単です。次のような呼び出しの間でオプションをリセットする必要があります。

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

ええ、私はそれを知っています。問題は 'GET'や' HEAD'メソッドではなく 'PUT'の後に' POST'を送る時です。 – tcurvelo

+0

これは、私が説明したのと同じ動作です。正しいオプションを設定するだけです。 –

+0

libcurlの場合、 'CURLOPT_NOBODY'は' HEAD'を意味し、 'CURLOPT_HTTPGET'は' GET'を意味します。 OK?私が示したコードでは、すでに 'send_a_post()'関数で新しいリクエストタイプを 'CURLOPT_POST'に設定しています。 – tcurvelo

関連する問題