在HTTP POST请求中向Slack发送JSON

在HTTP POST请求中向Slack发送JSON,json,api,slack-api,Json,Api,Slack Api,我正在尝试使用API调用发送消息。我在HTTPGET中编码测试消息没有问题,但我正试图在HTTPPOST请求中使用JSON实现相同的结果 我一直在使用curl和进行测试,但Slack似乎根本不承认我的请求主体 { "ok": false, "error": "not_authed" } 在curl中,我的请求编码如下: curl -H "Content-type: application/json" -X POST -d '{"token":"my-token-here","chann

我正在尝试使用API调用发送消息。我在HTTPGET中编码测试消息没有问题,但我正试图在HTTPPOST请求中使用JSON实现相同的结果

我一直在使用
curl
和进行测试,但Slack似乎根本不承认我的请求主体

{
  "ok": false,
  "error": "not_authed"
}
curl
中,我的请求编码如下:

curl -H "Content-type: application/json" -X POST -d '{"token":"my-token-here","channel":"#channel-name-or-id","text":"Text here.","username":"otherusername"}'
在《邮递员》中,这是原始的身体:

{
    "token":"my-token-here",
    "channel":"#channel-name-or-id",
    "text":"Text here.",
    "username":"otherusername"
}

我以前从未做过类似的事情,所以我不确定我是否遗漏了什么。谢谢

未认证
表示未提供认证令牌


您在请求中传递哪个令牌?您需要传递OAuth令牌,您可以从中获取该令牌。

尝试将每个属性放入其自己的-d参数中,如下所示:

curl https://slack.com/api/chat.postMessage -X POST -d "channel=#tehchannel" -d "text=teh text" -d "username=teh user" -d "token=teh-token-you-got-from-teh-page-that-machinehead115-linked-to" -d "icon_emoji=:simple_smile:"

我有点晚了,但我希望这能帮助其他像我一样陷入这个问题的人。我刚和Slack联系过,他们是这么告诉我的:

SlackWebAPI根本不接受JSON数据,因此在更改内容类型的同时,应该使用标准HTTP表单属性发布这些变量

我们计划将来支持JSON数据,以确保将来的一致性

因此,您的卷曲线应该如下所示:

curl -X POST -d 'token=my-token-here&channel=#channel-name-or-id&text=Text here.&username=otherusername'`

我希望这有帮助!:)

这可能不符合完整答案的条件,但如果目的是发送邮件附件,则可以发送
urlencode
d JSON结构作为
attachments
参数的值,如下所示(为了清楚起见,分成多行):


附件的值是URL编码的
[{“color”:“good”,“fallback”:“plain text”,“text”:“colored text”}]
。您应该能够使用所有附件属性。

Slack已更新,现在可以使用了。试试这个例子:

curl -X POST -H 'Content-type: application/json' --data '{"text":"This is a line of text.\nAnd this is another one."}' https://hooks.slack.com/services/AAAAAA/BBBBBB/CCCCCC

有关文档,请参阅。

我在powershell中完成了这项工作,它的工作非常出色

$url="https://slack.com/api/chat.postMessage"
    $messageContent= # your message here
    $token = # your token here
    $channel = # channel name
    $opt_username= # optional user name

    $body = @{token=$token;channel=$channel;username=$opt_username;text=$messageContent;pretty=1}

    try
    {
        Invoke-WebRequest -Uri $url -Method POST -Body $body
    }
    catch
    {
        Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ 
        Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription        
    }

如果您使用的是java和spring这样的依赖关系,瞧!!给你

     * Make a POST call to the chat.PostMessage.
     */
    public void chatPostMessage(Message message)
    {
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        map.add("token", slackPostMessageToken); //Required
        map.add("text", message.getText());//Required
        map.add("channel", message.getChannelId());//Required

        map.add("unfurl_links","true");
        map.add("as_user","false");//Default false
        map.add("icon_emoji",":chart_with_upwards_trend:");
        map.add("attachments","[\n" +
                "        {\n" +
                "            \"fallback\": \"Required plain-text summary of the attachment.\",\n" +
                "            \"color\": \"#36a64f\",\n" +
                "            \"pretext\": \"Optional text that appears above the attachment block\",\n" +
                "            \"author_name\": \"Bobby Tables\",\n" +
                "            \"author_link\": \"http://flickr.com/bobby/\",\n" +
                "            \"author_icon\": \"http://flickr.com/icons/bobby.jpg\",\n" +
                "            \"title\": \"Slack API Documentation\",\n" +
                "            \"title_link\": \"https://api.slack.com/\",\n" +
                "            \"text\": \"Optional text that appears within the attachment\",\n" +
                "            \"fields\": [\n" +
                "                {\n" +
                "                    \"title\": \"Priority\",\n" +
                "                    \"value\": \"High\",\n" +
                "                    \"short\": false\n" +
                "                }\n" +
                "            ],\n" +
                "            \"image_url\": \"http://my-website.com/path/to/image.jpg\",\n" +
                "            \"thumb_url\": \"http://example.com/path/to/thumb.png\",\n" +
                "            \"footer\": \"Datoo ©\",\n" +
                "            \"ts\": "+System.currentTimeMillis()+"" +
                "        }\n" +
                "    ]");
        map.add("username","III");


        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(slackPostMessageUrl, request, String.class);
            System.out.println(response);
        }
        catch (RestClientException e) {
            logger.error("Error :-( : ", e);
        }
    }
*对chat.PostMessage进行POST呼叫。
*/
公共void chatPostMessage(消息消息消息)
{
RestTemplate RestTemplate=新RestTemplate();
HttpHeaders=新的HttpHeaders();
headers.setContentType(MediaType.APPLICATION\u FORM\u URLENCODED);
MultiValueMap=新链接的MultiValueMap();
map.add(“token”,slackPostMessageToken);//必需
map.add(“text”,message.getText());//必需
map.add(“channel”,message.getChannelId());//必需
添加(“展开链接”、“真实”);
add(“as_user”,“false”);//默认值false
添加(“图标表情符号”):带有向上趋势的图表;
map.add(“附件”,“[\n”+
“{\n”+
“\”回退\“:\”所需的附件纯文本摘要。\”,\n”+
“颜色”:“36a64f\”,\n+
“\”借口\“:\”出现在附件块上方的可选文本\“,\n”+
“\”作者\姓名\“:\”博比表格\“,\n”+
“\”作者链接\“:\”http://flickr.com/bobby/\“,\n”+
“\”作者\图标\“:\”http://flickr.com/icons/bobby.jpg\“,\n”+
“\”标题\“:\”松弛API文档\“,\n”+
“\“标题链接\”:\”https://api.slack.com/\“,\n”+
“\”文本\“:\”出现在附件中的可选文本\“,\n”+
“\“字段\”:[\n”+
“{\n”+
“标题”:“优先级”,\n+
“值”:“高”,\n+
“\“short\”:false\n”+
“}\n”+
“],\n”+
“\“图像\ url\”:\”http://my-website.com/path/to/image.jpg\“,\n”+
“\“拇指url\”:\”http://example.com/path/to/thumb.png\“,\n”+
“\'footer\:\'Datoo©\”,\n”+
“\“ts\”:“+System.currentTimeMillis()+”+
“}\n”+
"    ]");
地图。添加(“用户名”、“III”);
HttpEntity请求=新的HttpEntity(映射、头);
试一试{
ResponseEntity response=restTemplate.postForEntity(slackPostMessageUrl、请求、String.class);
System.out.println(响应);
}
捕获(RestClientException e){
logger.error(“error:-(:”,e);
}
}

好的,重新阅读文档后,我发现:

JSON编码体

对于这些写方法,您也可以发送HTTP POST 数据作为内容类型:application/json

有一些基本规则:

  • 您必须显式地将内容类型HTTP头设置为application/json。没有它,我们将不会解释您的文章正文
  • 您必须在授权HTTP头中将令牌作为承载令牌传输
  • 您不能将令牌作为查询字符串的一部分或作为发布的JSON中的属性发送
  • 不要在查询字符串、URL编码的帖子正文和JSON属性之间混用参数。请为每个请求选择一种方法
  • 为属性提供显式空值将导致为其指定任何默认行为
还有
curl
示例。请注意Authorization标题

curl -X POST \
     -H 'Authorization: Bearer xoxb-1234-56789abcdefghijklmnop' \
     -H 'Content-type: application/json; charset=utf-8' \
    --data '{"channel":"C061EG9SL","text":""..."}' \
https://slack.com/api/chat.postMessage

在“邮递员”上,您可以这样描述您的请求:

curl -H "Content-type: application/json" -X POST -d '{"token":"my-token-here","channel":"#channel-name-or-id","text":"Text here.","username":"otherusername"}'
网址(张贴):

然后在
标题下
部分放置以下两个标题:

  • 键(
    Content-Type
    )值(
    application/json

  • 密钥(
    Authorization
    )值(
    YOUR-TOKEN-NAME

  • 然后在
    raw
    表单的
    Body
    部分中输入数据:

        {"channel": "CHANNEL-NAME", "data": "You better post this to channel"}
    

    截至2018年3月,Sl
    curl -X POST -H 'Authorization: Bearer xoxb-41234078565-14457098702432-ZLJj9UFOZKnOJtjNW4dv3ukG'  -H 'Content-type: application/json; charset=utf-8'  --data '{"channel":"#general","text":"I hope the tour went well, Mr. Wonka."}' https://slack.com/api/chat.postMessage