[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。
ただいまコメントを受けつけておりません。
Slack の API を叩くとき「発言だけできればいい」という状況であれば WebHock の利用を検討するべきだろう(Incoming Webhooks | Slack)。Java から WebHock を叩きたい事情があったので叩くコードを書いてみた。
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class SlackWebhockNotificationClient {
private final URL url;
private final String userName;
public SlackWebhockNotificationClient(URL url, String userName) {
this.url = url;
this.userName = userName;
}
public void sendNotify(String message) throws IOException {
HttpURLConnection con = null;
try {
con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
writer.write(String.format("payload={\"username\": \"%s\", \"text\": \"%s\", \"icon_emoji\": \":rooster:\"}", userName, message));
writer.flush();
if(con.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException(String.format("Failed to access %s :" + con.getResponseCode(), this.url));
}
} catch (IOException ioe) {
throw ioe;
}
}
}
SlackWebhockNotificationClient client = new SlackWebhockNotificationClient(
// https://slack.com/services/new/incoming-webhook から取得する URL
"https://hooks.slack.com/services/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",
// 発言する名前
"My Notification Bot"
);
client.sendNotify("発言だよー発言だよー");
ただいまコメントを受けつけておりません。