libcurl http get request in json format

2019-05-29 14:02发布

问题:

Is there a way to send a HTTP get request using libcurl in JSON format?

My current request is

curl_easy_setopt(curl_handle, CURLOPT_URL, "http://localhost:9200/_search?q=tag:warcraft")

using libcurl. It's equivalent in curl is

curl -XGET http://localhost:9200/_all/tweet/_search?q=tag:warcraft

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" }
    }
}'

I would like to know the equivalent libcurl code to send the above request. Thanks.

回答1:

you should use CURLOPT_POSTFIELDS

curl_easy_setopt(curl, CURLOPT_POST, 1); 
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data_encoded_as_string);

The -d option is used for POST method. From the curl man page

-d, --data Sends the specified data in a POST request to the HTTP server

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)

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.

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)


回答2:

Following kalyan's advice, this is the code I ended up with. Posting this for completion.

int main() {

     CURL *curl_handle;     
     CURLcode res;

    static const char *postthis="{\"query\":{\"term\":{\tag\":\"warcraft\"}}}";
    curl_global_init(CURL_GLOBAL_ALL);
    curl_handle = curl_easy_init();

    if(curl_handle) {

        curl_easy_setopt(curl_handle, CURLOPT_URL, "http://localhost:9200/_search");
        curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, postthis);

        curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE, (long)strlen(postthis));
        curl_easy_setopt(curl_handle, CURLOPT_WRITEHEADER, stdout);
        curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, stdout);

        res = curl_easy_perform(curl_handle);
        if(res != CURLE_OK)
                  fprintf(stderr, "curl_easy_perform() failed: %s\n",
                                        curl_easy_strerror(res));
        curl_easy_cleanup(curl_handle);
        return 0;
    }
}