Home > Blockchain >  How can I pass args to a curl request executed via boost::process:child?
How can I pass args to a curl request executed via boost::process:child?

Time:03-03

I'm able to execute a http POST request using curl via boost::process::child by passing the entire command line. However, I would like to pass the arguments via boost::process::args but I cannot get it work.

This works:

const std::string cmdDiscord = "curl -X POST https://discord.com:443/api/webhooks/1234567890 -H \"content-type: application/json\" -d \"{\"content\": \"test\"}\"";

boost::process::child c(cmdDiscord);                         // this works
boost::process::child c(boost::process::cmd = cmdDiscord);   // strangely, this doesn't work

I want to use boost::process::args but this fails:

std::vector<std::string> argsDiscord {"-X POST",
                                      "https://discord.com:443/api/webhooks/1234567890",
                                      "-H \"content-type: application/json\"",
                                      "-d \"{\"content\": \"test\"}\""};

boost::process::child c(boost::process::search_path("curl"), boost::process::args (argsDiscord));

The error is curl: (55) Failed sending HTTP POST request which is quite a vague error message. I couldn't find any examples calling curl. Does anyone have any suggestions on getting this to work?

CodePudding user response:

It should be

std::vector<std::string> argsDiscord {"-X", "POST",
                                      "https://discord.com:443/api/webhooks/1234567890",
                                      "-H", "content-type: application/json",
                                      "-d", "{\"content\": \"test\"}"};

Since command interpretators pass arguments like -X POST are two arguments, not one.

The double quotes are a shell syntax as well. The shell interprets (removes) them during command line expansion.

Alternatively curl accepts adjacent values in short options (without space)

std::vector<std::string> argsDiscord {"-XPOST",
                                      "https://discord.com:443/api/webhooks/1234567890",
                                      "-H", "content-type: application/json",
                                      "-d", "{\"content\": \"test\"}"};
  • Related