我的代码如下,但是没有作用,HTTP Server端不能接收到PUT的数据:
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);
}
后来经过搜索发现,不能使用:
curl_easy_setopt(curl, CURLOPT_PUT, 1L);
需要使用定制的请求,并且使用 POSTFIELDS发送数据。新的PUT请求代码如下:
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);
}
如果你想阻止从HTTP服务端发送回来的回复或者想进一步解析回复数据,需要设置 CURLOPT_WRITEFUNCTION用于接收数据或者设置 CURLOPT_WRITEDATA 指向文件或接收内存的地址。
原版链接:http://stackoverflow.com/questions/7569826/send-string-in-put-request-with-libcurl