c++ - 使用 libcurl 创建 InfluxDB 数据库的 HTTP post

标签 c++ http-post libcurl influxdb

我正在尝试使用 libcurl 库制作一个 http 帖子来创建一个 InfluxDB 数据库,如他们的网站所示:

curl -i -XPOST http://localhost:8086/query --data-urlencode "q=CREATE DATABASE mydb"

看来我的代码不起作用。它没有给我任何错误,但没有创建数据库。但是相反,如果我尝试向现有数据库添加一些点,具有相同的功能,它就可以工作。我想我错过了添加“q=CREATE DATABASE mydb”部分的正确方法。我应该如何更改我的代码?

int main(int argc, char *argv[]){

       char *url = "http://localhost:8086/query";
       char *data = "q=CREATE DATABASE mydb";
       /* should i change data string to json? 
          data = "{\"q\":\"CREATE DATABASE mydb\" }" */

       bool res = createInfluxDB(url, data);

       /*control result*/ 

       return(0);
}

bool createInfluxDB(char *url, char *data) {
      CURL *curl;

      curl = curl_easy_init();

      if(curl) {
        CURLcode res;
        /* What Content-type should i use?*/
        struct curl_slist* headers = curl_slist_append(headers, "Content-Type: application/json");
        /*--data-urlencode*/
        char *urlencoded = curl_easy_escape(curl, data, int(strlen(data)));

        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, urlencoded);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(urlencoded));

        res = curl_easy_perform(curl);

        /*omitted controls*/

        curl_free(urlencoded);
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
      }

      return(true);
    }

最佳答案

在分析了带有 http post 请求(返回错误请求)的数据包之后,我发现我不应该将查询参数添加为数据。但它应该是 url 的一部分。所以在像这样更改代码后,它就可以工作了!

int main(int argc, char *argv[]){

   char *url = "http://localhost:8086/query?q=CREATE+DATABASE+mydb";
   bool res = createInfluxDB(url);

   /*control result*/ 

   return(0);
}

bool createInfluxDB(char *url) {
  CURL *curl;

  curl = curl_easy_init();

  if(curl) {
    CURLcode res;
    struct curl_slist* headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");

    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    res = curl_easy_perform(curl);

    /*omitted controls*/

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
  }

  return(true);
}

关于c++ - 使用 libcurl 创建 InfluxDB 数据库的 HTTP post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49131732/

相关文章:

c++ - 我需要在新类中声明构造函数和析构函数吗?

jquery - POST 使用 JQuery 工作,但不能使用 Angularjs

c# - 如何在 asp.net 应用程序中从 jquery 设置 HttpPost 端点

php 单 curl 有效但多 curl 不起作用?

c++ - 创建 libcurl http post 表单

c++ - cURL - 将输出放入整数变量

c++ - 流类的基类

C++:去虚拟化叶子类

android - HttpPost 请求返回错误响应

c++ - OpenCV 寻找轮廓