Last active
May 20, 2019 04:55
-
-
Save seratch/c0272ac3df8a37f175524c32f21e67d1 to your computer and use it in GitHub Desktop.
Call Slack APIs with no deps in Java 11+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.seratch; | |
import java.net.URI; | |
import java.net.URLEncoder; | |
import java.net.http.HttpClient; | |
import java.net.http.HttpRequest; | |
import java.net.http.HttpResponse; | |
import java.nio.charset.StandardCharsets; | |
import java.util.Map; | |
public class App { | |
public static void main(String[] args) throws Exception { | |
String token = System.getenv("SLACK_BOT_TOKEN"); | |
HttpClient httpClient = HttpClient.newHttpClient(); | |
Map<String, ?> params = Map.of( | |
"token", token, | |
"channel", "#random", // using channel id is better, though | |
"text", "java.net.http.HttpClient works!" | |
); | |
HttpRequest request = HttpRequest.newBuilder() | |
.uri(URI.create("https://slack.com/api/chat.postMessage")) | |
.POST(HttpRequest.BodyPublishers.ofString(toRequestBody(params))) | |
.header("Content-Type", "application/x-www-form-urlencoded") | |
.build(); | |
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); | |
System.out.println("status: " + response.statusCode() + ", body: " + response.body()); | |
} | |
public static String toRequestBody(Map<String, ?> params) { | |
StringBuilder sb = new StringBuilder(); | |
for (String key : params.keySet()) { | |
if (sb.length() > 0) { | |
sb.append("&"); | |
} | |
sb.append(URLEncoder.encode(key, StandardCharsets.UTF_8)); | |
sb.append("="); | |
Object value = params.get(key); | |
if (value != null) { | |
sb.append(URLEncoder.encode(String.valueOf(value), StandardCharsets.UTF_8)); | |
} | |
} | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment