-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAPIRequest.java
More file actions
85 lines (69 loc) · 2.12 KB
/
Copy pathAPIRequest.java
File metadata and controls
85 lines (69 loc) · 2.12 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
84
85
package com.ptisp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
public class APIRequest {
private String url = null;
private String username = null;
private String password = null;
public APIRequest(String url, String username, String password) {
this.url = url;
this.username = username;
this.password = password;
}
public void setURL(String url) {
this.url = url;
}
public JSONObject execute() {
return execute(false);
}
public JSONObject execute(boolean isPost) {
try {
HttpClient client = new DefaultHttpClient();
String base64EncodedCredentials = Base64.encodeBytes((username + ":" + password).getBytes());
HttpRequestBase req;
if (isPost) {
req = new HttpPost(url);
} else {
req = new HttpGet(url);
}
req.addHeader("Authorization", "Basic " + base64EncodedCredentials);
HttpResponse response = client.execute(req);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String respondebody = convertStreamToString(is);
try {
return new JSONObject(respondebody);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
} catch (IOException e) {
e.printStackTrace();
} finally {
is.close();
}
return sb.toString();
}
}
}