/
OkHttpClient.java
204 lines (180 loc) · 6.54 KB
/
OkHttpClient.java
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
/*
* Copyright 2012-2023 The Feign Authors
*
* 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.okhttp;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import feign.AsyncClient;
import feign.Client;
import feign.Request.HttpMethod;
import feign.Request.ProtocolVersion;
import okhttp3.*;
import static feign.Util.enumForName;
/**
* This module directs Feign's http requests to
* <a href="http://square.github.io/okhttp/">OkHttp</a>, which enables SPDY and better network
* control. Ex.
*
* <pre>
* GitHub github = Feign.builder().client(new OkHttpClient()).target(GitHub.class,
* "https://api.github.com");
*/
public final class OkHttpClient implements Client, AsyncClient<Object> {
private final okhttp3.OkHttpClient delegate;
public OkHttpClient() {
this(new okhttp3.OkHttpClient());
}
public OkHttpClient(okhttp3.OkHttpClient delegate) {
this.delegate = delegate;
}
static Request toOkHttpRequest(feign.Request input) {
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url(input.url());
MediaType mediaType = null;
boolean hasAcceptHeader = false;
for (String field : input.headers().keySet()) {
if (field.equalsIgnoreCase("Accept")) {
hasAcceptHeader = true;
}
for (String value : input.headers().get(field)) {
requestBuilder.addHeader(field, value);
if (field.equalsIgnoreCase("Content-Type")) {
mediaType = MediaType.parse(value);
if (input.charset() != null) {
mediaType.charset(input.charset());
}
}
}
}
// Some servers choke on the default accept string.
if (!hasAcceptHeader) {
requestBuilder.addHeader("Accept", "*/*");
}
byte[] inputBody = input.body();
if (input.httpMethod().isWithBody()) {
requestBuilder.removeHeader("Content-Type");
if (inputBody == null) {
// write an empty BODY to conform with okhttp 2.4.0+
// http://johnfeng.github.io/blog/2015/06/30/okhttp-updates-post-wouldnt-be-allowed-to-have-null-body/
inputBody = new byte[0];
}
}
RequestBody body = inputBody != null ? RequestBody.create(mediaType, inputBody) : null;
requestBuilder.method(input.httpMethod().name(), body);
return requestBuilder.build();
}
private static feign.Response toFeignResponse(Response response, feign.Request request)
throws IOException {
return feign.Response.builder()
.protocolVersion(enumForName(ProtocolVersion.class, response.protocol()))
.status(response.code())
.reason(response.message())
.request(request)
.headers(toMap(response.headers()))
.body(toBody(response.body()))
.build();
}
private static Map<String, Collection<String>> toMap(Headers headers) {
return (Map) headers.toMultimap();
}
private static feign.Response.Body toBody(final ResponseBody input) throws IOException {
if (input == null || input.contentLength() == 0) {
if (input != null) {
input.close();
}
return null;
}
final Integer length = input.contentLength() >= 0 && input.contentLength() <= Integer.MAX_VALUE
? (int) input.contentLength()
: null;
return new feign.Response.Body() {
@Override
public void close() throws IOException {
input.close();
}
@Override
public Integer length() {
return length;
}
@Override
public boolean isRepeatable() {
return false;
}
@Override
public InputStream asInputStream() throws IOException {
return input.byteStream();
}
@SuppressWarnings("deprecation")
@Override
public Reader asReader() throws IOException {
return input.charStream();
}
@Override
public Reader asReader(Charset charset) throws IOException {
return asReader();
}
};
}
private okhttp3.OkHttpClient getClient(feign.Request.Options options) {
okhttp3.OkHttpClient requestScoped;
if (delegate.connectTimeoutMillis() != options.connectTimeoutMillis()
|| delegate.readTimeoutMillis() != options.readTimeoutMillis()
|| delegate.followRedirects() != options.isFollowRedirects()) {
requestScoped = delegate.newBuilder()
.connectTimeout(options.connectTimeoutMillis(), TimeUnit.MILLISECONDS)
.readTimeout(options.readTimeoutMillis(), TimeUnit.MILLISECONDS)
.followRedirects(options.isFollowRedirects())
.build();
} else {
requestScoped = delegate;
}
return requestScoped;
}
@Override
public feign.Response execute(feign.Request input, feign.Request.Options options)
throws IOException {
okhttp3.OkHttpClient requestScoped = getClient(options);
Request request = toOkHttpRequest(input);
Response response = requestScoped.newCall(request).execute();
return toFeignResponse(response, input).toBuilder().request(input).build();
}
@Override
public CompletableFuture<feign.Response> execute(feign.Request input,
feign.Request.Options options,
Optional<Object> requestContext) {
okhttp3.OkHttpClient requestScoped = getClient(options);
Request request = toOkHttpRequest(input);
CompletableFuture<feign.Response> responseFuture = new CompletableFuture<>();
requestScoped.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
responseFuture.completeExceptionally(e);
}
@Override
public void onResponse(Call call, okhttp3.Response response)
throws IOException {
final feign.Response r =
toFeignResponse(response, input).toBuilder().request(input).build();
responseFuture.complete(r);
}
});
return responseFuture;
}
}