使用libcurl创建InfluxDB数据库的HTTP帖子

问题描述 投票:1回答:2

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

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

看起来我的代码不起作用。它没有给我任何错误,但没有创建db。但相反,如果我尝试将一些点添加到现有数据库,具有相同的功能,它的工作原理。我想我错过了添加“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);
    }
c++ http-post libcurl influxdb
2个回答
1
投票

在使用http post请求(返回错误请求)分析数据包之后,我到达了我不应该将查询参数添加为数据的点。但相反它应该是网址的一部分。所以改变这样的代码后,它就可以了!

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

0
投票

编辑答案:

你在if语句中仍然有一个名不一致的var:

if (urlencode) free(...

那应该是

if (urlencoded) free(...

然后在您的标题中将应用程序类型设置为json,我不认为这是您想要的。像“application / x-www-form-urlencoded”这样的东西可能更好。

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

原始答案:

一个解决方法可能在你的

char *data = curl_easy_escape(curl, json, int(strlen(json)));

那个带有json var的重载数据不存在?

这样的事情可能会更好:

data = curl_easy_escape(curl, data, int(strlen(data)));
© www.soinside.com 2019 - 2024. All rights reserved.