libcurl http获取请求以json格式 [英] libcurl http get request in json format
问题描述
有没有办法使用libcurl以JSON格式发送HTTP get请求?
Is there a way to send a HTTP get request using libcurl in JSON format?
我当前的请求是
curl_easy_setopt(curl_handle,CURLOPT_URL,http:// localhost:9200 / _search?q = tag:warcraft)
使用libcurl。它等价于curl是
using libcurl. It's equivalent in curl is
curl -XGET http://localhost:9200/_all/tweet/_search?q=tag:warcraft
我想使用libcurl发送以下curl请求>
I would like to send the following curl request (in json format) using libcurl.
curl -XGET http://localhost:9200/_search -d '{
"query" : {
"term" : { "tag": "warcraft" }
}
}'
我想知道等效的libcurl代码来发送上面的请求。感谢。
I would like to know the equivalent libcurl code to send the above request. Thanks.
推荐答案
您应该使用CURLOPT_POSTFIELDS
you should use CURLOPT_POSTFIELDS
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data_encoded_as_string);
-d选项用于POST方法。从curl手册页
The -d option is used for POST method. From the curl man page
-d,--data将POST请求中指定的数据发送到
HTTP服务器
-d, --data Sends the specified data in a POST request to the HTTP server
如果您需要发送更多不适合查询字符串的数据,您必须使用POST方法
If you need to send more data that can not fit in a query string you have to use POST method
http://en.wikipedia.org/wiki/POST_ (HTTP)
作为GET请求的一部分,一些数据可以在URI的
查询字符串,指定例如搜索项,日期范围或
定义查询的其他信息。作为POST请求的一部分,
可以在
请求消息正文中将任意类型的任意数量的数据发送到服务器。
As part of a GET request, some data can be passed within the URI's query string, specifying for example search terms, date ranges, or other information that defines the query. As part of a POST request, an arbitrary amount of data of any type can be sent to the server in a request message body.
如果你严格地使用GET(?)形式的url以这样的方式把你的json数据在查询字符串本身。
If you strictly have to use GET (?) form your url in such a way to put your json data in the query string itself.
query_string = "q=" + json_encoded_to_str
curl_easy_setopt(curl_handle, CURLOPT_URL, "http://localhost:9200/_search?" + query_string)
这篇关于libcurl http获取请求以json格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!