Skip to content

Commit c50e711

Browse files
authored
Merge pull request #1 from ChunMengLu/master
支持 java 11 HttpClient
2 parents 7b2547d + 2915dde commit c50e711

File tree

10 files changed

+354
-12
lines changed

10 files changed

+354
-12
lines changed

README.md

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,5 @@
2121

2222
## 特点
2323

24-
- 默认会按照下面的优先级自行寻找底层实现,`OkHttp3 -> httpclient -> hutool-http`
24+
- 默认会按照下面的优先级自行寻找底层实现,java 11 HttpClient -> OkHttp3 -> apache HttpClient -> hutool-http
2525
- 也可以自行实现 `com.xkcoding.http.support.Http` 接口,通过 `HttpUtil.setHttp(new MyHttpImpl())` 设置进来
26-
27-
## TODO
28-
29-
- [ ] 集成 JDK11 的 HTTPClient
30-

pom.xml

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
1919
<maven.compiler.source>1.8</maven.compiler.source>
2020
<maven.compiler.target>1.8</maven.compiler.target>
21-
2221
<okhttp3.version>4.2.2</okhttp3.version>
2322
<httpclient.version>4.5.10</httpclient.version>
2423
<hutool.version>5.1.0</hutool.version>
@@ -85,6 +84,49 @@
8584
</dependencies>
8685

8786
<build>
87+
<plugins>
88+
<!-- 支持多个 source -->
89+
<plugin>
90+
<groupId>org.codehaus.mojo</groupId>
91+
<artifactId>build-helper-maven-plugin</artifactId>
92+
<version>3.0.0</version>
93+
<executions>
94+
<execution>
95+
<id>add-source</id>
96+
<phase>generate-sources</phase>
97+
<goals>
98+
<goal>add-source</goal>
99+
</goals>
100+
<configuration>
101+
<sources>
102+
<source>src/main/java11</source>
103+
</sources>
104+
</configuration>
105+
</execution>
106+
</executions>
107+
</plugin>
108+
<plugin>
109+
<artifactId>maven-jar-plugin</artifactId>
110+
<executions>
111+
<execution>
112+
<id>default-jar</id>
113+
<phase>package</phase>
114+
<goals>
115+
<goal>jar</goal>
116+
</goals>
117+
</execution>
118+
</executions>
119+
<!-- 排除 java 11 source -->
120+
<configuration>
121+
<excludes>
122+
<exclude>java</exclude>
123+
<exclude>java/net</exclude>
124+
<exclude>java/net/http</exclude>
125+
<exclude>java/net/http/*</exclude>
126+
</excludes>
127+
</configuration>
128+
</plugin>
129+
</plugins>
88130
<pluginManagement>
89131
<plugins>
90132
<plugin>

src/main/java/com/xkcoding/http/HttpUtil.java

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,16 +40,21 @@ public class HttpUtil {
4040

4141
static {
4242
Http defaultProxy = null;
43+
ClassLoader classLoader = HttpUtil.class.getClassLoader();
44+
// java 11 HttpClient
45+
if (ClassUtil.isPresent("java.net.http.HttpClient", classLoader)) {
46+
defaultProxy = new com.xkcoding.http.support.java11.HttpClientImpl();
47+
}
4348
// 基于 okhttp3
44-
if (ClassUtil.isPresent("okhttp3.OkHttpClient", HttpUtil.class.getClassLoader())) {
49+
if (ClassUtil.isPresent("okhttp3.OkHttpClient", classLoader)) {
4550
defaultProxy = new OkHttp3Impl();
4651
}
4752
// 基于 httpclient
48-
else if (ClassUtil.isPresent("org.apache.http.impl.client.HttpClients", HttpUtil.class.getClassLoader())) {
53+
else if (ClassUtil.isPresent("org.apache.http.impl.client.HttpClients", classLoader)) {
4954
defaultProxy = new HttpClientImpl();
5055
}
5156
// 基于 hutool
52-
else if (ClassUtil.isPresent("cn.hutool.http.HttpRequest", HttpUtil.class.getClassLoader())) {
57+
else if (ClassUtil.isPresent("cn.hutool.http.HttpRequest", classLoader)) {
5358
defaultProxy = new HutoolImpl();
5459
}
5560
proxy = defaultProxy;

src/main/java/com/xkcoding/http/constants/Constants.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,16 @@ public interface Constants {
4343
*/
4444
String CONTENT_TYPE_JSON = "application/json; charset=utf-8";
4545

46+
/**
47+
* Content-Type
48+
*/
49+
String CONTENT_TYPE = "Content-Type";
50+
51+
/**
52+
* Content-Encoding
53+
*/
54+
String CONTENT_ENCODING = "Content-Encoding";
55+
4656
/**
4757
* 空字符串
4858
*/

src/main/java/com/xkcoding/http/support/httpclient/HttpClientImpl.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,10 @@ public HttpClientImpl() {
5454
this.httpClient = HttpClients.createDefault();
5555
}
5656

57+
public HttpClientImpl(CloseableHttpClient httpClient) {
58+
this.httpClient = httpClient;
59+
}
60+
5761
private String exec(HttpRequestBase request) {
5862
// 设置超时时长
5963
request.setConfig(RequestConfig.custom()
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
/*
2+
* Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & www.dreamlu.net).
3+
* <p>
4+
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
* <p>
8+
* http://www.gnu.org/licenses/lgpl.html
9+
* <p>
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 com.xkcoding.http.support.java11;
18+
19+
import com.xkcoding.http.constants.Constants;
20+
import com.xkcoding.http.support.Http;
21+
import com.xkcoding.http.support.HttpHeader;
22+
import com.xkcoding.http.util.MapUtil;
23+
import com.xkcoding.http.util.StringUtil;
24+
25+
import java.io.IOException;
26+
import java.net.URI;
27+
import java.net.http.HttpClient;
28+
import java.net.http.HttpRequest;
29+
import java.net.http.HttpResponse;
30+
import java.time.Duration;
31+
import java.util.Map;
32+
33+
/**
34+
* java 11 HttpClient
35+
*
36+
* @author L.cm
37+
*/
38+
public class HttpClientImpl implements Http {
39+
private final HttpClient client;
40+
41+
public HttpClientImpl() {
42+
this(HttpClient.newBuilder().connectTimeout(Duration.ofMillis(Constants.TIMEOUT)).build());
43+
}
44+
45+
public HttpClientImpl(HttpClient client) {
46+
this.client = client;
47+
}
48+
49+
private String exec(HttpRequest request) {
50+
try {
51+
return client.send(request, HttpResponse.BodyHandlers.ofString()).body();
52+
} catch (IOException | InterruptedException e) {
53+
throw new RuntimeException(e);
54+
}
55+
}
56+
57+
/**
58+
* GET 请求
59+
*
60+
* @param url URL
61+
* @return 结果
62+
*/
63+
@Override
64+
public String get(String url) {
65+
return this.get(url, null, false);
66+
}
67+
68+
/**
69+
* GET 请求
70+
*
71+
* @param url URL
72+
* @param params 参数
73+
* @param encode 是否需要 url encode
74+
* @return 结果
75+
*/
76+
@Override
77+
public String get(String url, Map<String, String> params, boolean encode) {
78+
return this.get(url, params, null, encode);
79+
}
80+
81+
/**
82+
* GET 请求
83+
*
84+
* @param url URL
85+
* @param params 参数
86+
* @param header 请求头
87+
* @param encode 是否需要 url encode
88+
* @return 结果
89+
*/
90+
@Override
91+
public String get(String url, Map<String, String> params, HttpHeader header, boolean encode) {
92+
String baseUrl = StringUtil.appendIfNotContain(url, "?", "&");
93+
String reqUrl = baseUrl + MapUtil.parseMapToString(params, encode);
94+
95+
HttpRequest.Builder builder = HttpRequest.newBuilder()
96+
.uri(URI.create(reqUrl))
97+
.GET()
98+
.timeout(Duration.ofMillis(Constants.TIMEOUT));
99+
100+
if (header != null) {
101+
MapUtil.forEach(header.getHeaders(), builder::header);
102+
}
103+
104+
return exec(builder.build());
105+
}
106+
107+
/**
108+
* POST 请求
109+
*
110+
* @param url URL
111+
* @return 结果
112+
*/
113+
@Override
114+
public String post(String url) {
115+
return this.post(url, null);
116+
}
117+
118+
/**
119+
* POST 请求
120+
*
121+
* @param url URL
122+
* @param data JSON 参数
123+
* @return 结果
124+
*/
125+
@Override
126+
public String post(String url, String data) {
127+
return this.post(url, data, null);
128+
}
129+
130+
/**
131+
* POST 请求
132+
*
133+
* @param url URL
134+
* @param data JSON 参数
135+
* @param header 请求头
136+
* @return 结果
137+
*/
138+
@Override
139+
public String post(String url, String data, HttpHeader header) {
140+
HttpRequest.Builder builder = HttpRequest.newBuilder()
141+
.uri(URI.create(url))
142+
.POST(HttpRequest.BodyPublishers.noBody())
143+
.timeout(Duration.ofMillis(Constants.TIMEOUT));
144+
145+
if (StringUtil.isNotEmpty(data)) {
146+
builder.POST(HttpRequest.BodyPublishers.ofString(data, Constants.DEFAULT_ENCODING));
147+
builder.header(Constants.CONTENT_ENCODING, Constants.DEFAULT_ENCODING.displayName());
148+
builder.header(Constants.CONTENT_TYPE, Constants.CONTENT_TYPE_JSON);
149+
} else {
150+
builder.POST(HttpRequest.BodyPublishers.noBody());
151+
}
152+
153+
if (header != null) {
154+
MapUtil.forEach(header.getHeaders(), builder::header);
155+
}
156+
157+
return this.exec(builder.build());
158+
}
159+
160+
/**
161+
* POST 请求
162+
*
163+
* @param url URL
164+
* @param params form 参数
165+
* @param encode 是否需要 url encode
166+
* @return 结果
167+
*/
168+
@Override
169+
public String post(String url, Map<String, String> params, boolean encode) {
170+
return this.post(url, params, null, encode);
171+
}
172+
173+
/**
174+
* POST 请求
175+
*
176+
* @param url URL
177+
* @param params form 参数
178+
* @param header 请求头
179+
* @param encode 是否需要 url encode
180+
* @return 结果
181+
*/
182+
@Override
183+
public String post(String url, Map<String, String> params, HttpHeader header, boolean encode) {
184+
String baseUrl = StringUtil.appendIfNotContain(url, "?", "&");
185+
String reqUrl = baseUrl + MapUtil.parseMapToString(params, encode);
186+
return this.post(reqUrl, null, header);
187+
}
188+
}

src/main/java/com/xkcoding/http/support/okhttp3/OkHttp3Impl.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,17 @@ public class OkHttp3Impl implements Http {
3939
private final OkHttpClient httpClient;
4040
public static final MediaType CONTENT_TYPE_JSON = MediaType.get(Constants.CONTENT_TYPE_JSON);
4141

42+
4243
public OkHttp3Impl() {
43-
this.httpClient = new OkHttpClient().newBuilder()
44+
this(new OkHttpClient().newBuilder()
4445
.connectTimeout(Duration.ofMillis(Constants.TIMEOUT))
4546
.writeTimeout(Duration.ofMillis(Constants.TIMEOUT))
4647
.readTimeout(Duration.ofMillis(Constants.TIMEOUT))
47-
.build();
48+
.build());
49+
}
50+
51+
public OkHttp3Impl(OkHttpClient httpClient) {
52+
this.httpClient = httpClient;
4853
}
4954

5055
private String exec(Request request) {
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package java.net.http;
2+
3+
import java.io.IOException;
4+
import java.time.Duration;
5+
6+
/**
7+
* For the Java 8 compatibility when compiled with JDK 11+.
8+
*
9+
* @author L.cm
10+
*/
11+
public abstract class HttpClient {
12+
13+
public static HttpClient.Builder newBuilder() {
14+
return null;
15+
}
16+
17+
public abstract <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler) throws IOException, InterruptedException;
18+
19+
public interface Builder {
20+
Builder connectTimeout(Duration duration);
21+
22+
HttpClient build();
23+
}
24+
}

0 commit comments

Comments
 (0)