c ++通过系统在shell中运行curl

时间:2015-07-31 14:22:02

标签: c++ shell curl

如果我在shell中写这个,那么一切都像魅力一样:

// shell (unix)
curl -X PUT -d "{ \"string\" : \"my string 1212 \"}" "https://my.firebaseio.com/myVal.json"

正如您所知,这会在我的firebase中插入一些内容。如上所述,这可以按预期工作。由于我不是太深入C ++,我不知道如何PUT curl - 内部请求。我正考虑通过system在shell中执行此操作。

我最终得到了这个:

// c++ code
system('curl -X PUT -d "{ \"string\" : \"my string 1212 \"}" "https://my.firebaseio.com/myVal.json" ');

然而,这产生了这个输出:

curl: (6) Could not resolve host: 
curl: (6) Could not resolve host: CD
curl: (7) Could not resolve host: CD
curl: (3) [globbing] unmatched close brace/bracket in column 1

感谢您提供任何有用的建议

//更新1

在听说单个引号'被保留用于字符并转到提供的解决方案时,它仍然是相同的输出:

curl: (6) Could not resolve host: 
curl: (6) Could not resolve host: cd
curl: (7) Could not resolve host: cd
curl: (3) [globbing] unmatched close brace/bracket in column 1
{
   "error" : "Invalid data; couldn't parse JSON object, array, or value. Perhaps you're using invalid characters in your key names."
}

1 个答案:

答案 0 :(得分:3)

在C ++中,单引号用于char类型。双引号保留给std::stringchar * s。

因此,您的解决方案应该是简单地用双引号替换单引号并转义不是最终引用的引号:

system("curl -X PUT -d \"{ \"string\" : \"my string 1212 \"}\" https://my.firebaseio.com/myVal.json ");

但是,就像@DaoWen所提到的那样,如果可能的话,总是使用库。

编辑

我建议尝试这个:

std::string command = "curl -X PUT -d \"{ \"string\" : \"my string 1212 \"}\" https://my.firebaseio.com/myVal.json ";

system(command.c_str());

但老实说,如果您不想使用fork,最好使用execlibcurl来电而非系统通话。

编辑2

std::string command = "curl -H \"Content-Type: application/json\" -X PUT -d '{ \"string\" : \"my string 1212 \"}' https://my.firebaseio.com/myVal.json";

system(command.c_str());

奇怪的逃脱报价是对待关键:"字符串"作为主机,因为{被引号包围,充当数据。我通过用单引号包围要传递的数据来解决这个问题。

您可以看到我PUT { "Hello" : "World!" }到您的应用here

希望这会有所帮助。