有没有办法使用 libcurl 以 JSON 格式发送 HTTP get 请求?
我目前的要求是
curl_easy_setopt(curl_handle, CURLOPT_URL, "http://localhost:9200/_search?q=tag:warcraft")
使用 libcurl。它等同于 curl 是
curl -XGET http://localhost:9200/_all/tweet/_search?q=tag:warcraft
我想使用 libcurl 发送以下 curl 请求(json 格式)。
curl -XGET http://localhost:9200/_search -d '{
"query" : {
"term" : { "tag": "warcraft" }
}
}'
我想知道发送上述请求的等效 libcurl 代码。谢谢。
最佳答案
你应该使用 CURLOPT_POSTFIELDS
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data_encoded_as_string);
-d 选项用于 POST 方法。来自 curl 手册页
-d, --data Sends the specified data in a POST request to the HTTP server
如果您需要发送更多的数据,而这些数据无法放入查询字符串中,您必须使用 POST 方法
http://en.wikipedia.org/wiki/POST_(HTTP)
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 (?) 以将您的 json 数据放入查询字符串本身的方式形成您的 url。
query_string = "q=" + json_encoded_to_str
curl_easy_setopt(curl_handle, CURLOPT_URL, "http://localhost:9200/_search?" + query_string)
关于c - libcurl http get json 格式的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13236479/