使用libcurl上传文件(将curl命令传给libcurl)

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

如何将 curl 命令的这一部分传输到 libcurl 请求?我的主要问题是如何正确上传文件。

curl -d @path/to/data.json https://reqbin.com/echo/post/json

我尝试做的是使用:

curl_formadd(&post, &last, CURLFORM_COPYNAME, "file",
            CURLFORM_FILECONTENT, "ecg.scp", CURLFORM_END);

但是我收到“错误请求”响应。

有人知道如何将此命令传输到 libcurl 代码吗?

c++ curl post request libcurl
1个回答
0
投票

根据 curl 的 文档,单独使用

-d @path/to/data.json
POST
data.json
的内容使用
application/x-www-form-urlencoded
格式。但是,您不能使用该格式上传文件,它只适合发布
name=value
对。

根据这个 ReqBin 页面(将 JSON 发布到服务器),您要发布到的 URL 期望原始 JSON 原样采用

application/json
格式。 此 ReqBin 页面(使用 Curl 发布 JSON)显示使用以下 curl 命令将 JSON 发布到该 URL,这与您显示的命令有点不同:

使用 Curl 发布 JSON

 curl -X POST https://reqbin.com/echo/post/json
   -H 'Content-Type: application/json'
   -d '{"login":"my_login","password":"my_password"}'

至少,在您的情况下,该命令看起来更像这样:

curl -X POST https://reqbin.com/echo/post/json
  -H 'Content-Type: application/json'
  -d @path/to/data.json

在 libcurl 中,它看起来像这样:

#include <curl/curl.h>
#include <string>
 
std::string json;
// read data.json into string, see:
// https://stackoverflow.com/questions/116038/

CURL *curl = curl_easy_init();
struct curl_slist *slist = curl_slist_append(NULL, "Content-Type: application/json"); 
curl_easy_setopt(curl, CURLOPT_URL, "https://reqbin.com/echo/post/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist); 
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, json.size());
curl_easy_perform(curl);
...
curl_slist_free_all(slist);
curl_easy_cleanup(curl);
© www.soinside.com 2019 - 2024. All rights reserved.