团队,我需要帮助向Slack发布一个简单的Json请求。我设置了配置并使用了URL。他们希望我添加payload={"Text":"Some String"}
我正在使用以下代码:
HttpPost httppost = new HttpPost("slackURL");
httppost.addHeader("Content-type", "application/json");
StringEntity params = new StringEntity("payload={\"text\" : \""+message+"\"}","UTF-8");
params.setContentType("application/json");
httppost.setEntity(params);
错误消息:
HTTP/1.1 500 Server Error
Response content length: -1
Chunked?: true
来自Slack的回应:
Our logs indicate that the content isn't being posted to the payload HTTP POST/form parameter.
答案 0 :(得分:1)
更改
StringEntity params = new StringEntity("payload={\"text\" : \""+message+"\"}","UTF-8");
到
StringEntity params = new StringEntity("{\"text\" : \""+message+"\"}","UTF-8");
(摆脱“payload =”,因为那是无效的JSON。)
每the documentation,在发送到传入的webhook网址时有两种选择:
payload
表单编码参数。你在做什么之间......你声称要发送一个JSON编码的主体(通过Content-Type: application/json
),但你没有发送有效的JSON。 (您发送的内容看起来更像是表单编码选项,但实际上并没有对其进行表单编码。)
作为旁注:我强烈建议您使用真正的库来构建JSON。手动操作很容易出错。例如,如果您尝试对消息A wise man once said "You shouldn't try to encode JSON by hand."
进行编码,则会因为您生成的JSON无效而收到错误。