我的代码是这样的:
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);
}
这是行不通的,程序永远挂起。
在 test.php 中,这些是我得到的请求 header :
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"
}
但是正文是空的,意味着请求没有发送json数据。
我想用 libcurl 做的实际上就是这些命令行脚本:
curl -X PUT -H "Content-Type: application/json" -d '... some json ...' 127.0.0.1/test.php
最佳答案
明白了:)
不要使用
curl_easy_setopt(curl, CURLOPT_PUT, 1L);
发出自定义请求并将数据作为 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);
}
关于c - 使用 libcurl 在 PUT 请求中发送字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7569826/