-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.java
More file actions
73 lines (67 loc) · 2.54 KB
/
API.java
File metadata and controls
73 lines (67 loc) · 2.54 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
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;
public class API {
private static API instance=new API();
private API(){}
public static API getInstance(){
if(instance == null) instance = new API();
return instance;
}
public JSONObject callAPI(String strUrl, String method, Map<String,String> header, Map<String,String> body) throws MalformedURLException {
URL url;
HttpURLConnection con;
try {
url = new URL(strUrl);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(method);
if(header!=null) {
header.entrySet().stream().forEach(e->con.setRequestProperty(e.getKey(),e.getValue()));
}
con.setDoOutput(true);
con.setDoInput(true);
if(body!=null) {
JSONObject params = new JSONObject();
body.entrySet().forEach(e->{
params.put(e.getKey(),e.getValue());
});
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
wr.write(params.toString());
wr.flush();
}
int responseCode=con.getResponseCode();
if(responseCode==HttpURLConnection.HTTP_OK){
BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
JSONObject responseJson = new JSONObject();
JSONParser jsonParser=new JSONParser();
responseJson=(JSONObject) jsonParser.parse(sb.toString());
con.disconnect();
return responseJson;
}
else{
con.disconnect();
System.out.println("Error Code : "+responseCode);
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}