gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:04:02 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com