POST 通过 libcurl 的请求失败

POST request via libcurl is failing

卷曲https://connect.insteon.com/api/v2/commands\ -X POST \ -H "Content-Type: application/json" \ -H "Authentication: APIKey $API_KEY" \ -H "Authorization: Bearer $ACCESS_TOKEN" --data-binary '{"command":"on","level":75,"device_id":67890}'

这是控制 insteon 设备的 curl 命令,它在 linux 机器上通过终端完美运行。

我试图 运行 使用 CURL 命令进行相同的操作,但它抛出错误。 如果有人可以帮助我以 curl 命令格式发送上述请求,那将有很大帮助。

片段:

 curl_easy_setopt(curl, CURLOPT_URL, "https://connect.insteon.com/api/v2/commands");

 list = curl_slist_append(list, "Content-Type: application/json");

 list = curl_slist_append(list,"Authentication: APIKey XXXXXX");

 list = curl_slist_append(list,"Authorization: Bearer XXXXX");

 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);

/*I tried both PUT and POST as well*/

 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); /* !!! */

 curl_easy_setopt(curl, CURLOPT_POSTFIELDS,"--data-binary '{\"command\":\"on\",\"level\":75,\"device_id\":738486}'"); /* data goes here */
    res = curl_easy_perform(curl);
    if(res != CURLE_OK)
    {
            curl_easy_strerror(res);
    }
    curl_easy_cleanup(curl);

看起来还不错。

一个错误:删除 --data-binary:

 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"command\":\"on\",\"level\":75,\"device_id\":738486}"); /* data goes here */
 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, -1); /* curl uses strlen() to determine postfield-size */

这应该可以让它工作,否则 --data-binary 只是被复制到 post 数据中;)

我假设您使用 curl_easy_init 正确初始化了 curl,只是在您的代码段中遗漏了它。

编辑:添加了 CURLOPT_POSTFIELDSIZE

将 curl 命令行转换为 libcurl 源代码的最简单方法:

curl [all the options] --libcurl source.c

--libcurl source.c 部分将生成您的源代码模板,其中的选项设置与您的 curl 命令行相同。这通常会让你马上回家。