-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathHttpUtility.java
More file actions
183 lines (154 loc) · 8.5 KB
/
HttpUtility.java
File metadata and controls
183 lines (154 loc) · 8.5 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package com.skyflow.utils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.skyflow.errors.SkyflowException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
public final class HttpUtility {
private static final String LINE_FEED = "\r\n";
private static String requestID;
public static String getRequestID() {
return requestID;
}
public static String sendRequest(String method, URL url, JsonObject params, Map<String, String> headers) throws IOException, SkyflowException {
HttpURLConnection connection = null;
BufferedReader in = null;
StringBuffer response = null;
String boundary = String.valueOf(System.currentTimeMillis());
try {
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty(Constants.HttpHeader.ACCEPT, Constants.HttpHeader.ACCEPT_ALL);
boolean hasContentType = headers != null && headers.containsKey(Constants.HttpHeader.CONTENT_TYPE);
if (!hasContentType && params != null && !params.isEmpty()) {
connection.setRequestProperty(Constants.HttpHeader.CONTENT_TYPE, Constants.HttpHeader.CONTENT_TYPE_JSON);
}
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet())
connection.setRequestProperty(entry.getKey(), entry.getValue());
// append dynamic boundary if content-type is multipart/form-data
if (headers.containsKey(Constants.HttpHeader.CONTENT_TYPE)) {
if (Objects.equals(headers.get(Constants.HttpHeader.CONTENT_TYPE), Constants.HttpHeader.CONTENT_TYPE_MULTIPART)) {
connection.setRequestProperty(Constants.HttpHeader.CONTENT_TYPE, Constants.HttpHeader.CONTENT_TYPE_MULTIPART + Constants.HttpHeader.BOUNDARY_SEPARATOR + boundary);
}
}
}
if (params != null && !params.isEmpty()) {
connection.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
byte[] input = null;
String requestContentType = connection.getRequestProperty(Constants.HttpHeader.CONTENT_TYPE);
// Check if this is a raw body (XML, plain text, etc.)
if (params.has(Constants.HttpUtilityExtra.RAW_BODY_KEY) && params.size() == 1) {
input = params.get(Constants.HttpUtilityExtra.RAW_BODY_KEY).getAsString().getBytes(StandardCharsets.UTF_8);
} else if (requestContentType != null && requestContentType.contains(Constants.HttpHeader.CONTENT_TYPE_FORM_URLENCODED)) {
input = formatJsonToFormEncodedString(params).getBytes(StandardCharsets.UTF_8);
} else if (requestContentType != null && requestContentType.contains(Constants.HttpHeader.CONTENT_TYPE_MULTIPART)) {
input = formatJsonToMultiPartFormDataString(params, boundary).getBytes(StandardCharsets.UTF_8);
} else {
input = params.toString().getBytes(StandardCharsets.UTF_8);
}
wr.write(input, 0, input.length);
wr.flush();
}
}
int httpCode = connection.getResponseCode();
String requestID = connection.getHeaderField(Constants.REQUEST_ID_HEADER_KEY);
if (requestID != null) {
HttpUtility.requestID = requestID.split(Constants.HttpUtility.REQUEST_ID_DELIMITER)[0];
} else {
HttpUtility.requestID = Constants.HttpUtilityExtra.SDK_GENERATED_PREFIX + UUID.randomUUID();
}
Map<String, List<String>> responseHeaders = connection.getHeaderFields();
Reader streamReader;
if (httpCode > 299) {
if (connection.getErrorStream() != null)
streamReader = new InputStreamReader(connection.getErrorStream());
else {
String description = appendRequestId(Constants.HttpUtility.ERROR_DESCRIPTION, requestID);
throw new SkyflowException(description);
}
} else {
streamReader = new InputStreamReader(connection.getInputStream());
}
response = new StringBuffer();
in = new BufferedReader(streamReader);
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
if (httpCode > 299) {
throw new SkyflowException(httpCode, new Throwable(), responseHeaders, response.toString());
}
} finally {
if (in != null) {
in.close();
}
if (connection != null) {
connection.disconnect();
}
}
return response.toString();
}
public static String formatJsonToFormEncodedString(JsonObject requestBody) {
StringBuilder formEncodeString = new StringBuilder();
HashMap<String, String> jsonMap = convertJsonToMap(requestBody, "");
for (Map.Entry<String, String> currentEntry : jsonMap.entrySet())
formEncodeString.append(makeFormEncodeKeyValuePair(currentEntry.getKey(), currentEntry.getValue()));
return formEncodeString.substring(0, formEncodeString.length() - 1);
}
public static String formatJsonToMultiPartFormDataString(JsonObject requestBody, String boundary) {
StringBuilder formEncodeString = new StringBuilder();
HashMap<String, String> jsonMap = convertJsonToMap(requestBody, "");
for (Map.Entry<String, String> currentEntry : jsonMap.entrySet())
formEncodeString.append(makeFormDataKeyValuePair(currentEntry.getKey(), currentEntry.getValue(), boundary));
formEncodeString.append(LINE_FEED);
formEncodeString.append(Constants.FormData.BOUNDARY_SEPARATOR).append(boundary).append(Constants.FormData.BOUNDARY_SEPARATOR).append(LINE_FEED);
return formEncodeString.toString();
}
private static HashMap<String, String> convertJsonToMap(JsonObject json, String rootKey) {
HashMap<String, String> currentMap = new HashMap<>();
Map<String, JsonElement> jsonMap = json.asMap();
for (String key : jsonMap.keySet()) {
JsonElement currentValue = jsonMap.get(key);
String currentKey = !rootKey.isEmpty() ? rootKey + '[' + key + ']' : rootKey + key;
if (currentValue.isJsonObject()) {
currentMap.putAll(convertJsonToMap((JsonObject) currentValue, currentKey));
} else {
currentMap.put(currentKey, currentValue.getAsString());
}
}
return currentMap;
}
private static String makeFormDataKeyValuePair(String key, String value, String boundary) {
StringBuilder formDataTextField = new StringBuilder();
formDataTextField.append(Constants.FormData.BOUNDARY_SEPARATOR).append(boundary).append(LINE_FEED);
formDataTextField.append(Constants.HttpHeader.CONTENT_DISPOSITION).append(Constants.HttpHeader.FORM_DATA_HEADER).append(key).append("\"").append(LINE_FEED);
formDataTextField.append(LINE_FEED);
formDataTextField.append(value).append(LINE_FEED);
return formDataTextField.toString();
}
public static String appendRequestId(String message, String requestId) {
if (requestId != null && !requestId.isEmpty()) {
message = message + Constants.HttpUtility.REQUEST_ID_PREFIX + requestId;
}
return message;
}
private static String makeFormEncodeKeyValuePair(String key, String value) {
try {
String encodedKey = URLEncoder.encode(key, StandardCharsets.UTF_8.toString());
String encodedValue = URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
return encodedKey + Constants.HttpUtility.FORM_ENCODE_SEPARATOR + encodedValue + Constants.HttpUtility.FORM_ENCODE_DELIMITER;
} catch (Exception e) {
return key + Constants.HttpUtility.FORM_ENCODE_SEPARATOR + value + Constants.HttpUtility.FORM_ENCODE_DELIMITER;
}
}
}