如何在 c++ 中使用 libcurl 将 POST 发送到 elasticsearch

How to use libcurl in c++ to send POST to elasticsearch

本文关键字:POST elasticsearch libcurl c++      更新时间:2023-10-16

>有人知道将 Elasticsearch 与 libcurl 一起使用的确切语法吗?

#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
   CURL *curl;
   CURLcode res;
   curl = curl_easy_init();
   curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:9200/bro-201409170900/http/ZinAvJ-ETT-mycy2jyRkdg/_update -d");
   curl_easy_setopt(curl, CURLOPT_POST, 1);
   curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{"script" : "ctx._source.longitude += 3"}");
   curl_easy_perform(curl);
   curl_easy_cleanup(curl);
   return 1;
}

这段代码不会更新经度参数,我不知道为什么。

不应在 url 中指定 "-d"。命令行工具只是建立在libcurl之上。如果你想看看 post 请求的 c 代码是什么样子,你可以使用 libcurl 选项和命令行。

例:

curl localhost:9200/bro-201409170900/http/ZinAvJ-ETT-mycy2jyRkdg/… -d '{ "script" : "ctx._source.longitude += 2"}' --libcurl  output.c

一个简单的"C"实现看起来就像这些行一样

#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
   CURL *curl;
   CURLcode res;
   char *postFields = "{"script" : "ctx._source.longitude += 3"}";
   curl = curl_easy_init();
   curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
   curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:9200/bro-201409170900/http/ZinAvJ-ETT-mycy2jyRkdg/_update");
   curl_easy_setopt(curl, CURLOPT_POST, 1);
   curl_easy_setopt(curl,CURLOPT_POSTFIELDS,postFields);
   curl_easy_setopt(curl,CURLOPT_POSTFIELDSIZE,strlen(postFields));
   res = curl_easy_perform(curl);
   curl_easy_cleanup(curl);
   return res;
}