-1

How can I transfer this part of a curl command to a libcurl request? My main problem is how to correctly upload a file.

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

What I've tried to do is using:

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

But I get a "Bad request" response.

Does anyone have an idea of how to transfer this command to libcurl code?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

1

According to curl's documentation, using -d @path/to/data.json by itself will POST the content of data.json using the application/x-www-form-urlencoded format. But, you can't upload a file using that format, it is only good for posting name=value pairs.

According to this ReqBin page (Posting JSON to the Server), the URL you are posting to expects the raw JSON as-is in application/json format instead. And this ReqBin page (Posting JSON with Curl) shows posting JSON to that URL using the following curl command, which is a bit different than the command you have shown:

Posting JSON with Curl

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

At the very least, that command would look more like this in your case:

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

Which, in libcurl, would look something like this:

#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);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770