-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnector.java
55 lines (48 loc) · 2.25 KB
/
Connector.java
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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Connector {
private String serviceAccountKey = "xxx";
private String serviceAccountSecret = "xxx";
public String get(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String userpass = serviceAccountKey + ":" + serviceAccountSecret;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
int responseCode = conn.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + responseCode);
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String response = br.readLine();
conn.disconnect();
return response;
}
public String post(String urlString, String data) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String userpass = serviceAccountKey + ":" + serviceAccountSecret;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
conn.setRequestProperty("Authorization", basicAuth);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
os.flush();
int responseCode = conn.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + responseCode);
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String response = br.readLine();
conn.disconnect();
return response;
}
}