Java-向Slack Webhook发送消息

时间:2019-07-04 09:20:47

标签: java webhooks slack-api

我正在尝试使用Slack传入的Webhooks发送消息。我有以下代码。它可以运行,但是当我检查松弛情况时,没有任何消息。谁能看到我做错了什么。

public class SlackTest {

    static String web_hook_url = "https://hooks.slack.com/services/***********/******************";

    public static void main(String[] args) {


        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(web_hook_url);

        try {
            String json = "{\"name\": John}";
            System.out.println(json);
            StringEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            client.execute(httpPost);

            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}

1 个答案:

答案 0 :(得分:0)

我首先使用Postman测试发送邮件。然后使用Postman生成相应的Java代码。然后稍微调整一下代码,即可得出以下结果。 。 。

OkHttpClient client2 = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{ \"text\" : \"more text"\" }");
            Request request2 = new Request.Builder()
            .url("https://hooks.slack.com/services/********/*********/***************")
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "*/*")
                    .addHeader("Cache-Control", "no-cache")
                    .addHeader("Host", "hooks.slack.com")
                    .addHeader("accept-encoding", "gzip, deflate")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("cache-control", "no-cache")
                    .build();
Response response2 = client2.newCall(request2).execute();