2012-11-05 65 views
1

有沒有辦法使用JSON格式的libcurl發送HTTP請求?libcurl以json格式獲取請求

我的當前請求使用的libcurl是

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

。它相當於捲曲是

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代碼。謝謝。

回答

2

你應該使用CURLOPT_POSTFIELDS

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

-d選項用於POST方法。來自卷邊手冊頁

-d,--data發送的POST請求 HTTP服務器

如果需要發送無法適應查詢更多數據指定的數據字符串必須使用POST方法

http://en.wikipedia.org/wiki/POST_(HTTP)

作爲一個GET請求的一部分,一些數據可以內的URI的傳遞查詢字符串,指定例如搜索項,日期範圍或定義查詢的其他信息。作爲POST請求的一部分,任何類型的任意數量的數據可以通過 請求消息主體發送到服務器。

如果你嚴格地使用GET(?)來形成你的url,以這種方式把你的json數據放入查詢字符串本身。

query_string = "q=" + json_encoded_to_str 
curl_easy_setopt(curl_handle, CURLOPT_URL, "http://localhost:9200/_search?" + query_string) 
+0

我認爲CURLOPT_POST和CURLOPT_POSTFIELDS與http post請求有關。我需要一些HTTP GET請求。 –

+0

海事組織,不是一個好主意。但仍然可以實現。答案已更新。 – kalyan

+0

謝謝。我接受了使用POST方法的建議,並使其運行。我遵循這個代碼框架。 http://curl.haxx.se/libcurl/c/simplepost.html –

0

按照kalyan的建議,這是我結束的代碼。發佈此完成。

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; 
    } 
}