使用 libcurl 在 PUT 请求中发送字符串 [英] Send string in PUT request with libcurl
本文介绍了使用 libcurl 在 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);
}
这不起作用,程序只是永远挂起.
Which doesnt work, the program just hangs forever.
在 test.php 这些是我得到的请求标头:
In test.php these are the request headers I get:
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"
}
但是 body 是空的,意味着没有 json 数据与请求一起发送.
But the body is empty, means, no json data is sent with the request.
我想用 libcurl 做的实际上就是这些命令行脚本:
What I want to do with libcurl is actually nothing else then these command line script:
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 发送:
Make a custom request and send the data as 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);
}
这篇关于使用 libcurl 在 PUT 请求中发送字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文