在 HTTP POST 请求中将 JSON 发送到 Slack
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31905260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending JSON to Slack in a HTTP POST request
提问by Valentine
I'm trying to send a message using Slack's chat.postMessageAPI call. I have no problems encoding my test messages within HTTP GET, but I'm trying to achieve the same result with JSON in a HTTP POST request.
我正在尝试使用Slack 的 chat.postMessageAPI 调用发送消息。我在 HTTP GET 中编码我的测试消息没有问题,但我试图在 HTTP POST 请求中使用 JSON 实现相同的结果。
I've been testing with both curland Postman, but Slack doesn't seem to be acknowledging my request body at all.
我一直在测试curl和Postman,但 Slack 似乎根本不承认我的请求正文。
{
"ok": false,
"error": "not_authed"
}
In curl, my request is encoded like this:
在 中curl,我的请求是这样编码的:
curl -H "Content-type: application/json" -X POST -d '{"token":"my-token-here","channel":"#channel-name-or-id","text":"Text here.","username":"otherusername"}'
In Postman, this is the raw body:
在 Postman 中,这是原始主体:
{
"token":"my-token-here",
"channel":"#channel-name-or-id",
"text":"Text here.",
"username":"otherusername"
}
I haven't done anything like this before, so I'm not sure if I'm missing something out. Thanks!
我以前没有做过这样的事情,所以我不确定我是否遗漏了什么。谢谢!
回答by finferflu
I'm a bit late, but I hope this can help other people who stumble into this issue like me. I've just been in touch with Slack, and this is what they told me:
我有点晚了,但我希望这可以帮助其他像我一样偶然发现这个问题的人。我刚刚与 Slack 取得了联系,他们是这样告诉我的:
The Slack Web API doesn't accept JSON data at all — so along with changing the Content-Type those variables should be posted using standard HTTP form attributes.
We plan to support JSON data in the future for consistency in the future.
Slack Web API 根本不接受 JSON 数据——因此,除了更改 Content-Type 之外,还应使用标准 HTTP 表单属性发布这些变量。
我们计划在未来支持 JSON 数据以保证未来的一致性。
So, your cURL line should look like:
因此,您的 cURL 行应如下所示:
curl -X POST -d 'token=my-token-here&channel=#channel-name-or-id&text=Text here.&username=otherusername'`
I hope this helps! :)
我希望这有帮助!:)
回答by LSerni
Okay, after re-reading the documentation I found it:
好的,在重新阅读文档后,我找到了它:
JSON-encoded bodies
For these write methods, you may alternatively send your HTTP POST data as Content-type: application/json.
There are some ground rules:
- You must explicitly set the Content-type HTTP header to application/json. We won't interpret your POST body as such without it.
- You must transmit your token as a bearer token in the Authorization HTTP header.
- You cannot send your token as part of the query string or as an attribute in your posted JSON.
- Do not mix arguments between query string, URL-encoded POST body, and JSON attributes. Choose one approach per request.
- Providing an explicitly null value for an attribute will result in whichever default behavior is assigned to it.
JSON 编码的主体
对于这些写入方法,您也可以将 HTTP POST 数据作为 Content-type: application/json 发送。
有一些基本规则:
- 您必须将 Content-type HTTP 标头显式设置为 application/json。如果没有它,我们不会解释您的 POST 正文。
- 您必须在 Authorization HTTP 标头中将您的令牌作为不记名令牌传输。
- 您不能将您的令牌作为查询字符串的一部分或作为您发布的 JSON 中的属性发送。
- 不要在查询字符串、URL 编码的 POST 正文和 JSON 属性之间混合参数。为每个请求选择一种方法。
- 为属性提供明确的空值将导致为其分配任何默认行为。
And the curlexample. Notice the Authorizationheader.
和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
回答by mustaccio
This may not qualify for the complete answer, but if the purpose is to send a message attachment, you can send a urlencoded JSON structure as the value of the attachmentsparameter, like so (split into multiple lines for clarity):
这可能不符合完整的答案,但如果目的是发送消息附件,您可以发送一个urlencoded JSON 结构作为attachments参数的值,如下所示(为了清楚起见,分成多行):
https://slack.com/api/chat.postMessage?
token=YOUR-TOKE-N000&
channel=%23alerts&
text=Hi&
attachments=%5B%7B%22color%22%3A%22good%22%2C%22fallback%22%3A%22plain+text%22%2C%22text%22%3A%22colored+text%22%7D%5D
The value of attachmentsis URL-encoded [{"color":"good","fallback":"plain text","text":"colored text"}]. You should be able to use all attachment attributes described here.
的值attachments是 URL-encoded [{"color":"good","fallback":"plain text","text":"colored text"}]。您应该能够使用此处描述的所有附件属性。
回答by vnpnlz
As of March 2018, Slacknow supports POSTwith JSONbody
截至2018 年 3 月,Slack现在支持POSTwith JSONbody
Endpoint: https://slack.com/api/chat.postMessage
端点:https://slack.com/api/chat.postMessage
Headers: Authorization: Bearer xoxp-your-hardly-find-token-here
标题:Authorization: Bearer xoxp-your-hardly-find-token-here
Body: {"channel":"CH9NN37","text":"something from me!"}
身体:{"channel":"CH9NN37","text":"something from me!"}
Notice theBearerin theAuthorizationheader.
注意承载在授权报头中。
回答by Linus Proxy
Try putting each property in its own -d parameter, like so:
尝试将每个属性放在自己的 -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:"
回答by William Entriken
Slack has been updated, this now works. Try this example:
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
See https://api.slack.com/incoming-webhooksfor documentation.
回答by Umesh Poswal
On postman you can frame your request like this:
在邮递员上,您可以像这样构建您的请求:
url(POST) : https://slack.com/api/chat.postMessage
网址(POST):https: //slack.com/api/chat.postMessage
Then under Headerssection put these two headers:
然后在Headers部分下放置这两个标题:
key(
Content-Type) value(application/json)key(
Authorization) value(YOUR-TOKEN-NAME)
键(
Content-Type) 值(application/json)键(
Authorization) 值(YOUR-TOKEN-NAME)
Then in Bodysection in rawform put your data:
然后在表格Body部分raw放入您的数据:
{"channel": "CHANNEL-NAME", "data": "You better post this to channel"}
回答by machinehead115
回答by Tapan Banerjee
I did this in powershell and it works like a charm.
我在 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
}
回答by rbyndoor
If you are using java and spring such dependency, Voila!! here you go
如果你正在使用 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);
}
}

