c - libcurl http get json 格式的请求

标签 c http curl get libcurl

有没有办法使用 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/

相关文章:

c - 为什么不同 gcc 版本的简单 C 程序的汇编代码不同?

结构赋值可以像 memmove() 那样重叠,还是像 memcpy() 这样的结构赋值?

java - 用于 java 的谷歌安全浏览查找 api 代码

python - 使用 Python 的 SSL3 POST

curl - 使用 cURL 使用 JSON key 文件进行 Google Cloud 身份验证

c - 使用时钟循环链表的问题

c - 奇偶计数器

java - 读取请求使服务器停止

linux - curl 并检查 403 错误代码

perl - HTTP 响应 : Net/HTTP/Methods. pm 第 542 行中的错误 block 大小