使用libcurl在PUT请求中发送字符串

Max*_*Max 14 c curl

我的代码看起来像这样:

curl = curl_easy_init();

if (curl) {
    headers = curl_slist_append(headers, client_id_header);
    headers = curl_slist_append(headers, "Content-Type: application/json");

    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 
    curl_easy_setopt(curl, CURLOPT_URL, "127.0.0.1/test.php");  
    curl_easy_setopt(curl, CURLOPT_PUT, 1L);

    res = curl_easy_perform(curl);
    res = curl_easy_send(curl, json_struct, strlen(json_struct), &io_len);

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
}
Run Code Online (Sandbox Code Playgroud)

哪个不起作用,该程序永远挂起.

在test.php中,这些是我得到的请求标头:

array(6) {
  ["Host"]=>
  string(9) "127.0.0.1"
  ["Accept"]=>
  string(3) "*/*"
  ["Transfer-Encoding"]=>
  string(7) "chunked"
  ["X-ClientId"]=>
  string(36) "php_..."
  ["Content-Type"]=>
  string(16) "application/json"
  ["Expect"]=>
  string(12) "100-continue"
}
Run Code Online (Sandbox Code Playgroud)

但是身体是空的,意味着没有与请求一起发送的json数据.

我想用libcurl做的事实上就是这些命令行脚本:

curl -X PUT -H "Content-Type: application/json" -d '... some json ...' 127.0.0.1/test.php
Run Code Online (Sandbox Code Playgroud)

Max*_*Max 42

得到它了 :)

不要用

curl_easy_setopt(curl, CURLOPT_PUT, 1L);
Run Code Online (Sandbox Code Playgroud)

发出自定义请求并将数据作为POSTFIELDS发送:

curl = curl_easy_init();

if (curl) {
    headers = curl_slist_append(headers, client_id_header);
    headers = curl_slist_append(headers, "Content-Type: application/json");

    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 
    curl_easy_setopt(curl, CURLOPT_URL, request_url);  
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); /* !!! */

    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_struct); /* data goes here */

    res = curl_easy_perform(curl);

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么不使用CURLOPT_UPLOAD而不是CURLOPT_CUSTOMREQUEST,如[documentation](http://curl.haxx.se/libcurl/c/CURLOPT_PUT.html)所述? (3认同)