forked from gpedro/slack-webhook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSlackApi.java
More file actions
83 lines (65 loc) · 2.15 KB
/
SlackApi.java
File metadata and controls
83 lines (65 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package net.gpedro.integrations.slack;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import com.google.gson.JsonObject;
public class SlackApi {
private String service;
public SlackApi(String service) {
if(service == null) {
throw new IllegalArgumentException("Missing WebHook URL Configuration @ SlackApi");
} else if (!service.startsWith("https://hooks.slack.com/services/")) {
throw new IllegalArgumentException("Invalid Service URL. WebHook URL Format: https://hooks.slack.com/services/{id_1}/{id_2}/{token}");
}
this.service = service;
}
public void call(SlackMessage message) {
if(message != null) {
this.send(message.prepare());
}
}
private String send(JsonObject message) {
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(this.service);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
String payload = "payload="+URLEncoder.encode(message.toString(), "UTF-8");
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes(payload);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
System.out.println(response.toString());
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
}