C呼叫libcurl庫函式 查詢全文搜尋引擎 Elasticsearch
阿新 • • 發佈:2019-02-20
//執行在ubuntu64系統下
//curles.c
#include <stdio.h>
#include <curl/curl.h>
#include <string.h>
size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
strncat((char *)stream, (char *)ptr, size*nmemb);
return size * nmemb;
}
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.4.111:9200/database1/table1/_search"); //查詢ES的URL
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"query\": {\"match\": {\"title\": \"榮耀\"}}}"); //全文搜尋語句
char out[10240] = {0};
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
switch(res)
{
case CURLE_UNSUPPORTED_PROTOCOL:
fprintf(stderr,"不支援的協議,由URL的頭部指定\n");
case CURLE_COULDNT_CONNECT:
fprintf(stderr,"不能連線到remote主機或者代理\n");
case CURLE_HTTP_RETURNED_ERROR:
fprintf(stderr,"http返回錯誤\n");
case CURLE_READ_ERROR:
fprintf(stderr,"讀本地檔案錯誤\n");
default:
fprintf(stderr,"返回值:%d\n",res);
}
return -1;
}
printf("%s",out);
curl_easy_cleanup(curl);
return 1;
}
//gcc -o curles curles.c -lcrypto -lidn -lssl /usr/lib/x86_64-linux-gnu/libcurl.so.4