Skip to content

Commit f35ec53

Browse files
royclarksonbclozel
authored andcommitted
Add support for OkHttp3
OkHttp3 introduces a new package and API that is incompatible with previous versions. This commit adds a new OkHttp3ClientHttpRequestFactory and supporting classes.
1 parent d40d2ff commit f35ec53

11 files changed

+501
-5
lines changed

build.gradle

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ configure(allprojects) { project ->
6464
ext.jtaVersion = "1.2"
6565
ext.junitVersion = "4.12"
6666
ext.nettyVersion = "4.0.34.Final"
67+
ext.okhttp3Version = "3.2.0"
6768
ext.okhttpVersion = "2.7.5"
6869
ext.openjpaVersion = "2.4.1"
6970
ext.poiVersion = "3.14"
@@ -205,7 +206,7 @@ configure(allprojects) { project ->
205206
"http://www.eclipse.org/aspectj/doc/released/aspectj5rt-api/",
206207
"http://ehcache.org/apidocs/${ehcacheVersion}",
207208
"http://ehcache.org/apidocs/${ehcache3Version}",
208-
//"http://quartz-scheduler.org/api/2.2.0/",
209+
"http://quartz-scheduler.org/api/2.2.0/",
209210
"http://fasterxml.github.io/jackson-core/javadoc/2.7/",
210211
"http://fasterxml.github.io/jackson-databind/javadoc/2.7/",
211212
"http://fasterxml.github.io/jackson-dataformat-xml/javadoc/2.7/",
@@ -713,6 +714,7 @@ project("spring-web") {
713714
optional("org.apache.httpcomponents:httpclient:${httpclientVersion}")
714715
optional("org.apache.httpcomponents:httpasyncclient:${httpasyncVersion}")
715716
optional("io.netty:netty-all:${nettyVersion}")
717+
optional("com.squareup.okhttp3:okhttp:${okhttp3Version}")
716718
optional("com.squareup.okhttp:okhttp:${okhttpVersion}")
717719
optional("com.fasterxml.jackson.core:jackson-databind:${jackson2Version}")
718720
optional("com.fasterxml.jackson.dataformat:jackson-dataformat-xml:${jackson2Version}")
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/*
2+
* Copyright 2002-2016 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.http.client;
18+
19+
import java.io.IOException;
20+
import java.net.URI;
21+
22+
import okhttp3.Call;
23+
import okhttp3.Callback;
24+
import okhttp3.OkHttpClient;
25+
import okhttp3.Request;
26+
import okhttp3.Response;
27+
28+
import org.springframework.http.HttpHeaders;
29+
import org.springframework.http.HttpMethod;
30+
import org.springframework.util.concurrent.ListenableFuture;
31+
import org.springframework.util.concurrent.SettableListenableFuture;
32+
33+
/**
34+
* {@link AsyncClientHttpRequest} implementation that uses OkHttp to execute requests.
35+
*
36+
* <p>Created via the {@link OkHttpClientHttpRequestFactory}.
37+
*
38+
* @author Luciano Leggieri
39+
* @author Arjen Poutsma
40+
* @author Roy Clarkson
41+
* @since 4.3
42+
*/
43+
class OkHttp3AsyncClientHttpRequest extends AbstractBufferingAsyncClientHttpRequest {
44+
45+
private final OkHttpClient client;
46+
47+
private final URI uri;
48+
49+
private final HttpMethod method;
50+
51+
52+
public OkHttp3AsyncClientHttpRequest(OkHttpClient client, URI uri, HttpMethod method) {
53+
this.client = client;
54+
this.uri = uri;
55+
this.method = method;
56+
}
57+
58+
59+
@Override
60+
public HttpMethod getMethod() {
61+
return this.method;
62+
}
63+
64+
@Override
65+
public URI getURI() {
66+
return this.uri;
67+
}
68+
69+
@Override
70+
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers, byte[] content)
71+
throws IOException {
72+
73+
Request request = OkHttp3ClientHttpRequestFactory.buildRequest(headers, content, this.uri, this.method);
74+
return new OkHttpListenableFuture(this.client.newCall(request));
75+
}
76+
77+
78+
private static class OkHttpListenableFuture extends SettableListenableFuture<ClientHttpResponse> {
79+
80+
private final Call call;
81+
82+
public OkHttpListenableFuture(Call call) {
83+
this.call = call;
84+
this.call.enqueue(new Callback() {
85+
@Override
86+
public void onResponse(Call call, Response response) {
87+
set(new OkHttp3ClientHttpResponse(response));
88+
}
89+
@Override
90+
public void onFailure(Call call, IOException ex) {
91+
setException(ex);
92+
}
93+
});
94+
}
95+
96+
@Override
97+
protected void interruptTask() {
98+
this.call.cancel();
99+
}
100+
}
101+
102+
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*
2+
* Copyright 2002-2016 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.http.client;
18+
19+
import java.io.IOException;
20+
import java.net.URI;
21+
22+
import okhttp3.OkHttpClient;
23+
import okhttp3.Request;
24+
25+
import org.springframework.http.HttpHeaders;
26+
import org.springframework.http.HttpMethod;
27+
28+
/**
29+
* {@link ClientHttpRequest} implementation that uses OkHttp 3.x to execute requests.
30+
*
31+
* <p>Created via the {@link OkHttp3ClientHttpRequestFactory}.
32+
*
33+
* @author Luciano Leggieri
34+
* @author Arjen Poutsma
35+
* @author Roy Clarkson
36+
* @since 4.3
37+
*/
38+
class OkHttp3ClientHttpRequest extends AbstractBufferingClientHttpRequest {
39+
40+
private final OkHttpClient client;
41+
42+
private final URI uri;
43+
44+
private final HttpMethod method;
45+
46+
47+
public OkHttp3ClientHttpRequest(OkHttpClient client, URI uri, HttpMethod method) {
48+
this.client = client;
49+
this.uri = uri;
50+
this.method = method;
51+
}
52+
53+
54+
@Override
55+
public HttpMethod getMethod() {
56+
return this.method;
57+
}
58+
59+
@Override
60+
public URI getURI() {
61+
return this.uri;
62+
}
63+
64+
65+
@Override
66+
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] content) throws IOException {
67+
Request request = OkHttp3ClientHttpRequestFactory.buildRequest(headers, content, this.uri, this.method);
68+
return new OkHttp3ClientHttpResponse(this.client.newCall(request).execute());
69+
}
70+
71+
}
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
/*
2+
* Copyright 2002-2016 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.http.client;
18+
19+
import java.io.IOException;
20+
import java.net.MalformedURLException;
21+
import java.net.URI;
22+
import java.net.URL;
23+
import java.util.List;
24+
import java.util.Map;
25+
import java.util.concurrent.TimeUnit;
26+
27+
import okhttp3.OkHttpClient;
28+
import okhttp3.Request;
29+
import okhttp3.RequestBody;
30+
31+
import org.springframework.beans.factory.DisposableBean;
32+
import org.springframework.http.HttpHeaders;
33+
import org.springframework.http.HttpMethod;
34+
import org.springframework.util.Assert;
35+
import org.springframework.util.StringUtils;
36+
37+
/**
38+
* {@link ClientHttpRequestFactory} implementation that uses
39+
* <a href="http://square.github.io/okhttp/">OkHttp</a> 3.x to create requests.
40+
*
41+
* @author Luciano Leggieri
42+
* @author Arjen Poutsma
43+
* @author Roy Clarkson
44+
* @since 4.3
45+
*/
46+
public class OkHttp3ClientHttpRequestFactory
47+
implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory, DisposableBean {
48+
49+
private OkHttpClient client;
50+
51+
private final boolean defaultClient;
52+
53+
54+
/**
55+
* Create a factory with a default {@link OkHttpClient} instance.
56+
*/
57+
public OkHttp3ClientHttpRequestFactory() {
58+
this.client = new OkHttpClient();
59+
this.defaultClient = true;
60+
}
61+
62+
/**
63+
* Create a factory with the given {@link OkHttpClient} instance.
64+
* @param client the client to use
65+
*/
66+
public OkHttp3ClientHttpRequestFactory(OkHttpClient client) {
67+
Assert.notNull(client, "OkHttpClient must not be null");
68+
this.client = client;
69+
this.defaultClient = false;
70+
}
71+
72+
73+
/**
74+
* Sets the underlying read timeout in milliseconds.
75+
* A value of 0 specifies an infinite timeout.
76+
* @see okhttp3.OkHttpClient.Builder#readTimeout(long, TimeUnit)
77+
*/
78+
public void setReadTimeout(int readTimeout) {
79+
this.client = this.client.newBuilder()
80+
.readTimeout(readTimeout, TimeUnit.MILLISECONDS)
81+
.build();
82+
}
83+
84+
/**
85+
* Sets the underlying write timeout in milliseconds.
86+
* A value of 0 specifies an infinite timeout.
87+
* @see okhttp3.OkHttpClient.Builder#writeTimeout(long, TimeUnit)
88+
*/
89+
public void setWriteTimeout(int writeTimeout) {
90+
this.client = this.client.newBuilder()
91+
.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
92+
.build();
93+
}
94+
95+
/**
96+
* Sets the underlying connect timeout in milliseconds.
97+
* A value of 0 specifies an infinite timeout.
98+
* @see okhttp3.OkHttpClient.Builder#connectTimeout(long, TimeUnit)
99+
*/
100+
public void setConnectTimeout(int connectTimeout) {
101+
this.client = this.client.newBuilder()
102+
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
103+
.build();
104+
}
105+
106+
107+
@Override
108+
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) {
109+
return new OkHttp3ClientHttpRequest(this.client, uri, httpMethod);
110+
}
111+
112+
@Override
113+
public AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod) {
114+
return new OkHttp3AsyncClientHttpRequest(this.client, uri, httpMethod);
115+
}
116+
117+
118+
@Override
119+
public void destroy() throws IOException {
120+
if (this.defaultClient) {
121+
// Clean up the client if we created it in the constructor
122+
if (this.client.cache() != null) {
123+
this.client.cache().close();
124+
}
125+
this.client.dispatcher().executorService().shutdown();
126+
}
127+
}
128+
129+
130+
static Request buildRequest(HttpHeaders headers, byte[] content, URI uri,
131+
HttpMethod method) throws MalformedURLException {
132+
133+
okhttp3.MediaType contentType = getContentType(headers);
134+
RequestBody body = (content.length > 0 ? RequestBody.create(contentType, content) : null);
135+
136+
URL url = uri.toURL();
137+
String methodName = method.name();
138+
Request.Builder builder = new Request.Builder().url(url).method(methodName, body);
139+
140+
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
141+
String headerName = entry.getKey();
142+
for (String headerValue : entry.getValue()) {
143+
builder.addHeader(headerName, headerValue);
144+
}
145+
}
146+
147+
return builder.build();
148+
}
149+
150+
private static okhttp3.MediaType getContentType(HttpHeaders headers) {
151+
String rawContentType = headers.getFirst(HttpHeaders.CONTENT_TYPE);
152+
return (StringUtils.hasText(rawContentType) ? okhttp3.MediaType.parse(rawContentType) : null);
153+
}
154+
155+
}

0 commit comments

Comments
 (0)