Repository navigation
Expand file tree
/
Copy pathJavaNetHttpExecutor.java
More file actions
144 lines (131 loc) · 4.96 KB
/
Copy pathJavaNetHttpExecutor.java
File metadata and controls
144 lines (131 loc) · 4.96 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
package io.ipgeolocation.sdk.internal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public final class JavaNetHttpExecutor implements HttpExecutor {
private static final int DEFAULT_MAX_RESPONSE_BODY_CHARS = 128 * 1024 * 1024;
private final int connectTimeoutMillis;
private final int maxResponseBodyChars;
private final ConnectionFactory connectionFactory;
public JavaNetHttpExecutor(Duration connectTimeout) {
this(connectTimeout, DEFAULT_MAX_RESPONSE_BODY_CHARS, new DefaultConnectionFactory());
}
JavaNetHttpExecutor(Duration connectTimeout, ConnectionFactory connectionFactory) {
this(connectTimeout, DEFAULT_MAX_RESPONSE_BODY_CHARS, connectionFactory);
}
JavaNetHttpExecutor(
Duration connectTimeout,
int maxResponseBodyChars,
ConnectionFactory connectionFactory) {
Objects.requireNonNull(connectTimeout, "connectTimeout must not be null");
if (connectTimeout.isNegative() || connectTimeout.isZero()) {
throw new IllegalArgumentException("connectTimeout must be greater than zero");
}
if (maxResponseBodyChars <= 0) {
throw new IllegalArgumentException("maxResponseBodyChars must be greater than zero");
}
this.connectTimeoutMillis = toMillis(connectTimeout);
this.maxResponseBodyChars = maxResponseBodyChars;
this.connectionFactory =
Objects.requireNonNull(connectionFactory, "connectionFactory must not be null");
}
@Override
public HttpResponseData send(HttpRequestData request) throws IOException {
HttpURLConnection connection = connectionFactory.open(request.uri());
try {
connection.setConnectTimeout(connectTimeoutMillis);
connection.setReadTimeout(toMillis(request.timeout()));
connection.setRequestMethod(request.method());
applyHeaders(connection, request.headers());
writeBodyIfPresent(connection, request);
int statusCode = connection.getResponseCode();
return new HttpResponseData(
statusCode, readBody(connection, statusCode), connection.getHeaderFields());
} finally {
connection.disconnect();
}
}
private void applyHeaders(HttpURLConnection connection, Map<String, List<String>> headers) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
if (entry.getKey() == null || entry.getValue() == null) {
continue;
}
for (String value : entry.getValue()) {
if (value != null) {
connection.addRequestProperty(entry.getKey(), value);
}
}
}
}
private void writeBodyIfPresent(HttpURLConnection connection, HttpRequestData request)
throws IOException {
if (!"POST".equalsIgnoreCase(request.method()) && !"PUT".equalsIgnoreCase(request.method())) {
return;
}
byte[] payload = request.body().getBytes(StandardCharsets.UTF_8);
connection.setDoOutput(true);
if (connection.getRequestProperty("Content-Length") == null) {
connection.setFixedLengthStreamingMode(payload.length);
}
OutputStream outputStream = connection.getOutputStream();
try {
outputStream.write(payload);
outputStream.flush();
} finally {
outputStream.close();
}
}
private String readBody(HttpURLConnection connection, int statusCode) throws IOException {
InputStream stream =
statusCode >= 400 ? connection.getErrorStream() : connection.getInputStream();
if (stream == null) {
return "";
}
BufferedReader reader =
new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
try {
StringBuilder body = new StringBuilder();
char[] buffer = new char[2048];
int read;
int totalChars = 0;
while ((read = reader.read(buffer)) != -1) {
totalChars += read;
if (totalChars > maxResponseBodyChars) {
throw new IOException(
"Response body exceeded max size of " + maxResponseBodyChars + " characters");
}
body.append(buffer, 0, read);
}
return body.toString();
} finally {
reader.close();
}
}
private static int toMillis(Duration duration) {
if (duration.isNegative() || duration.isZero()) {
throw new IllegalArgumentException("timeout must be greater than zero");
}
if (duration.compareTo(Duration.ofMillis(Integer.MAX_VALUE)) >= 0) {
return Integer.MAX_VALUE;
}
return (int) Math.max(1L, duration.toMillis());
}
interface ConnectionFactory {
HttpURLConnection open(URI uri) throws IOException;
}
private static final class DefaultConnectionFactory implements ConnectionFactory {
@Override
public HttpURLConnection open(URI uri) throws IOException {
return (HttpURLConnection) uri.toURL().openConnection();
}
}
}