【问题标题】:Sending Slack message via windows Curl通过 windows Curl 发送 Slack 消息
【发布时间】:2020-12-08 14:03:06
【问题描述】:

我尝试在 C++ 控制台应用程序上使用 Slack API 和 curl 命令发送 Slack 消息,但由于字符串类型,我无法解决此错误:

curl命令(此命令成功发送消息)

curl -X POST -H "Content-type:application/json" --data "{\"text\":\"A New Program Has Just Been Posted!!!\"}" https://hooks.slack.com/services/{API_KEY}

C++ 代码:

#include <iostream>
#include <string>
int main()
{
    std::string command = "curl -X POST -H \"Content - type:application / json\" --data \"{\"text\":\"A New Program Has Just Been Posted!!!\"}\" https://hooks.slack.com/services/{API_KEY}";
    system(command.c_str());
    return 0;
}

正如您在这张图片上看到的,我无法发送消息(我需要查看 OK):

【问题讨论】:

    标签: c++ curl slack-api


    【解决方案1】:

    你需要更多的逃避。你已经逃脱了 "s 的 shell,但没有逃脱 "s 的 JSON。

    #include <iostream>
    #include <string>
    
    int main()
    {
        std::string command = "curl -X POST -H \"Content-Type: application/json\" --data \"{\\\"text\\\":\\\"A New Program Has Just Been Posted!!!\\\"}\" https://hooks.slack.com/services/{API_KEY}";
        system(command.c_str());
    }
    

    就像\" 是转义引号一样,\\ 是转义反斜杠。所以“双重转义”看起来像\\\"。呸!

    从 C++11 开始,使用原始字符串文字可能(也可能不会)更清晰,如下所示:

    #include <iostream>
    #include <string>
    
    int main()
    {
        std::string command = R"(curl -X POST -H "Content-Type: application/json" --data "{\"text\":\"A New Program Has Just Been Posted!!!\"}" https://hooks.slack.com/services/{API_KEY})";
        system(command.c_str());
    }
    

    (我还更正了您的 Content-Type 标头。)

    无论如何,我建议你使用 libcurl 而不是执行 shell 命令。

    【讨论】:

    • 是的,我需要更多的转义,但我怎样才能正确地做到这一点?
    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    相关资源
    最近更新 更多