Repository navigation
Expand file tree
/
Copy pathDefaultClient.java
More file actions
299 lines (272 loc) · 10.5 KB
/
Copy pathDefaultClient.java
File metadata and controls
299 lines (272 loc) · 10.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/*
* Copyright © 2012 The Feign Authors (feign@commonhaus.dev)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package feign;
import static feign.Util.ACCEPT_ENCODING;
import static feign.Util.CONTENT_ENCODING;
import static feign.Util.CONTENT_LENGTH;
import static feign.Util.ENCODING_DEFLATE;
import static feign.Util.ENCODING_GZIP;
import static java.lang.String.CASE_INSENSITIVE_ORDER;
import static java.lang.String.format;
import feign.Request.Options;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.InflaterInputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
/**
* {@link Client} backed by {@link HttpURLConnection}.
*
* <p>The request sent over the wire may differ from the {@link Request} reported by {@link Logger}.
* The JDK treats some headers as restricted (for example {@code Host}, {@code Connection} and
* {@code Content-Length}) and, unless the {@code sun.net.http.allowRestrictedHeaders} system
* property is set, ignores the values supplied for them, so the value on the wire may differ from
* the logged one. {@code Content-Length} is passed to {@link
* HttpURLConnection#setFixedLengthStreamingMode(int)} or computed by the JDK. An <code>
* Accept: */*</code> header is added when none is present, and a {@code Content-Encoding} of
* {@code gzip} or {@code deflate} compresses the body after it is logged.
*/
public class DefaultClient implements Client {
private static final int MAX_DRAIN_BYTES = 64 * 1024;
private static final int DRAIN_BUFFER_SIZE = 512;
private final SSLSocketFactory sslContextFactory;
private final HostnameVerifier hostnameVerifier;
/**
* Disable the request body internal buffering for {@code HttpURLConnection}.
*
* @see HttpURLConnection#setFixedLengthStreamingMode(int)
* @see HttpURLConnection#setFixedLengthStreamingMode(long)
* @see HttpURLConnection#setChunkedStreamingMode(int)
*/
private final boolean disableRequestBuffering;
/**
* Create a new client, which disable request buffering by default.
*
* @param sslContextFactory SSLSocketFactory for secure https URL connections.
* @param hostnameVerifier the host name verifier.
*/
public DefaultClient(SSLSocketFactory sslContextFactory, HostnameVerifier hostnameVerifier) {
this.sslContextFactory = sslContextFactory;
this.hostnameVerifier = hostnameVerifier;
this.disableRequestBuffering = true;
}
/**
* Create a new client.
*
* @param sslContextFactory SSLSocketFactory for secure https URL connections.
* @param hostnameVerifier the host name verifier.
* @param disableRequestBuffering Disable the request body internal buffering for {@code
* HttpURLConnection}.
*/
public DefaultClient(
SSLSocketFactory sslContextFactory,
HostnameVerifier hostnameVerifier,
boolean disableRequestBuffering) {
super();
this.sslContextFactory = sslContextFactory;
this.hostnameVerifier = hostnameVerifier;
this.disableRequestBuffering = disableRequestBuffering;
}
@Override
public Response execute(Request request, Options options) throws IOException {
HttpURLConnection connection = convertAndSend(request, options);
return convertResponse(connection, request);
}
Response convertResponse(HttpURLConnection connection, Request request) throws IOException {
int status = connection.getResponseCode();
String reason = connection.getResponseMessage();
if (status < 0) {
throw new IOException(
format(
"Invalid status(%s) executing %s %s",
status, connection.getRequestMethod(), connection.getURL()));
}
Map<String, Collection<String>> headers = new TreeMap<>(CASE_INSENSITIVE_ORDER);
for (Map.Entry<String, List<String>> field : connection.getHeaderFields().entrySet()) {
// response message
if (field.getKey() != null) {
headers.put(field.getKey(), field.getValue());
}
}
Integer length = connection.getContentLength();
if (length < 0) {
// -1 signals unknown or above Integer.MAX_VALUE; any other negative value is a malformed
// header that HttpURLConnection surfaces verbatim
length = null;
}
InputStream stream;
if (status >= 400) {
stream = connection.getErrorStream();
} else {
stream = connection.getInputStream();
}
if (stream != null && length == null) {
stream = new DrainOnCloseInputStream(stream);
}
if (stream != null && this.isGzip(headers.get(CONTENT_ENCODING))) {
stream = new GZIPInputStream(stream);
// the body is now decompressed, the Content-Length described the compressed bytes
length = null;
} else if (stream != null && this.isDeflate(headers.get(CONTENT_ENCODING))) {
stream = new InflaterInputStream(stream);
length = null;
}
return Response.builder()
.status(status)
.reason(reason)
.headers(headers)
.request(request)
.body(stream, length)
.build();
}
public HttpURLConnection getConnection(final URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
HttpURLConnection convertAndSend(Request request, Options options) throws IOException {
final URL url = new URL(request.url());
final HttpURLConnection connection = this.getConnection(url);
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection sslCon = (HttpsURLConnection) connection;
if (sslContextFactory != null) {
sslCon.setSSLSocketFactory(sslContextFactory);
}
if (hostnameVerifier != null) {
sslCon.setHostnameVerifier(hostnameVerifier);
}
}
connection.setConnectTimeout(options.connectTimeoutMillis());
connection.setReadTimeout(options.readTimeoutMillis());
connection.setAllowUserInteraction(false);
connection.setInstanceFollowRedirects(options.isFollowRedirects());
connection.setRequestMethod(request.httpMethod().name());
Collection<String> contentEncodingValues = request.headers().get(CONTENT_ENCODING);
boolean gzipEncodedRequest = this.isGzip(contentEncodingValues);
boolean deflateEncodedRequest = this.isDeflate(contentEncodingValues);
boolean hasAcceptHeader = false;
Integer contentLength = null;
for (String field : request.headers().keySet()) {
if (field.equalsIgnoreCase("Accept")) {
hasAcceptHeader = true;
}
for (String value : request.headers().get(field)) {
if (field.equalsIgnoreCase(CONTENT_LENGTH)) {
if (!gzipEncodedRequest && !deflateEncodedRequest) {
contentLength = Integer.valueOf(value);
}
}
// Avoid add "Accept-encoding" twice or more when "compression" option is enabled
else if (field.equals(ACCEPT_ENCODING)) {
connection.addRequestProperty(field, String.join(", ", request.headers().get(field)));
break;
} else {
connection.addRequestProperty(field, value);
}
}
}
// Some servers choke on the default accept string.
if (!hasAcceptHeader) {
connection.addRequestProperty("Accept", "*/*");
}
byte[] body = request.body();
if (body != null && body.length > 0) {
if (disableRequestBuffering) {
if (contentLength != null) {
connection.setFixedLengthStreamingMode(contentLength);
} else {
connection.setChunkedStreamingMode(8196);
}
}
connection.setDoOutput(true);
OutputStream out = connection.getOutputStream();
if (gzipEncodedRequest) {
out = new GZIPOutputStream(out);
} else if (deflateEncodedRequest) {
out = new DeflaterOutputStream(out);
}
try {
out.write(body);
} finally {
try {
out.close();
} catch (IOException suppressed) { // NOPMD
}
}
} else if (request.httpMethod().isWithBody()) {
/*
* Avoid calling connection.getOutputStream() for an empty body: HttpURLConnection defaults
* the Content-Type to application/x-www-form-urlencoded as soon as an output stream (a
* "poster") is created, even when zero bytes are written to it. Setting Content-Length
* directly ensures internal retry logic still applies to such requests, without triggering
* that default.
* To use this Header, set 'sun.net.http.allowRestrictedHeaders' property true.
*/
connection.addRequestProperty("Content-Length", "0");
}
return connection;
}
private static final class DrainOnCloseInputStream extends FilterInputStream {
private boolean closed;
DrainOnCloseInputStream(InputStream in) {
super(in);
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
closed = true;
try {
drain();
} catch (IOException ignored) { // NOPMD
} finally {
super.close();
}
}
private void drain() throws IOException {
if (in.read() == -1) {
return;
}
byte[] buffer = new byte[DRAIN_BUFFER_SIZE];
long drained = 1;
int read;
while (drained < MAX_DRAIN_BYTES && (read = in.read(buffer)) != -1) {
drained += read;
}
}
}
private boolean isGzip(Collection<String> contentEncodingValues) {
return contentEncodingValues != null
&& !contentEncodingValues.isEmpty()
&& contentEncodingValues.contains(ENCODING_GZIP);
}
private boolean isDeflate(Collection<String> contentEncodingValues) {
return contentEncodingValues != null
&& !contentEncodingValues.isEmpty()
&& contentEncodingValues.contains(ENCODING_DEFLATE);
}
}