forked from pcalcado/java-api-wrapper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttp.java
More file actions
79 lines (69 loc) · 2.38 KB
/
Http.java
File metadata and controls
79 lines (69 loc) · 2.38 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
package com.soundcloud.api;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
/**
* Helper class for various HTTP related functions.
*/
public class Http {
private Http() {
}
/**
* Returns a String representation of the response
*
* @param response an HTTP response
* @return the content body
* @throws IOException network error
*/
public static String getString(HttpResponse response) throws IOException {
InputStream is = response.getEntity().getContent();
if (is == null) return null;
int length = ApiWrapper.BUFFER_SIZE;
Header contentLength = null;
try {
contentLength = response.getFirstHeader(HTTP.CONTENT_LEN);
} catch (UnsupportedOperationException ignored) {
}
if (contentLength != null) {
try {
length = Integer.parseInt(contentLength.getValue());
} catch (NumberFormatException ignored) {
}
}
final StringBuilder sb = new StringBuilder(length);
int n;
byte[] buffer = new byte[ApiWrapper.BUFFER_SIZE];
while ((n = is.read(buffer)) != -1) sb.append(new String(buffer, 0, n));
return sb.toString();
}
public static JSONObject getJSON(HttpResponse response) throws IOException {
final String json = getString(response);
if (json == null || json.length() == 0) throw new IOException("JSON response is empty");
try {
return new JSONObject(json);
} catch (JSONException e) {
throw new IOException("could not parse JSON document: "+e.getMessage()+" "+
(json.length() > 80 ? (json.substring(0, 79) + "..." ) : json));
}
}
public static String etag(HttpResponse resp) {
Header etag = resp.getFirstHeader("Etag");
return etag != null ? etag.getValue() : null;
}
public static String formatJSON(String s) {
try {
return new JSONObject(s).toString(4);
} catch (JSONException e) {
try {
return new JSONArray(s).toString(4);
} catch (JSONException e2) {
return s;
}
}
}
}