Skip to content

Instantly share code, notes, and snippets.

@Depicus
Created December 26, 2014 13:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Depicus/d02834ac3c68a8862a3e to your computer and use it in GitHub Desktop.
Save Depicus/d02834ac3c68a8862a3e to your computer and use it in GitHub Desktop.
Sending Slack hook from Java
private static void sendSlackMessage(String message)
{
String url = "https://hooks.slack.com/services/your-token-here";
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(url);
JSONObject json = new JSONObject();
try {
json.put("channel", "#general");
json.put("text", message);
json.put("username", "#java-error-bot");
post.addParameter("payload", json.toString());
post.getParams().setContentCharset("UTF-8");
int responseCode = client.executeMethod(post);
String response = post.getResponseBodyAsString();
if (responseCode != HttpStatus.SC_OK) {
System.out.println("Slack post may have failed. Response: " + response);
}
} catch (JSONException e) {
System.out.println("JSONException posting to Slack " + e);
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException posting to Slack " + e);
} catch (IOException e) {
System.out.println("IOException posting to Slack " + e);
} finally {
post.releaseConnection();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment