Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

支持 java 11 HttpClient #1

Merged
merged 2 commits into from
Dec 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,5 @@

## 特点

- 默认会按照下面的优先级自行寻找底层实现,`OkHttp3 -> httpclient -> hutool-http`
- 默认会按照下面的优先级自行寻找底层实现,java 11 HttpClient -> OkHttp3 -> apache HttpClient -> hutool-http
- 也可以自行实现 `com.xkcoding.http.support.Http` 接口,通过 `HttpUtil.setHttp(new MyHttpImpl())` 设置进来

## TODO

- [ ] 集成 JDK11 的 HTTPClient

44 changes: 43 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

<okhttp3.version>4.2.2</okhttp3.version>
<httpclient.version>4.5.10</httpclient.version>
<hutool.version>5.1.0</hutool.version>
Expand Down Expand Up @@ -85,6 +84,49 @@
</dependencies>

<build>
<plugins>
<!-- 支持多个 source -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/java11</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<id>default-jar</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<!-- 排除 java 11 source -->
<configuration>
<excludes>
<exclude>java</exclude>
<exclude>java/net</exclude>
<exclude>java/net/http</exclude>
<exclude>java/net/http/*</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
Expand Down
11 changes: 8 additions & 3 deletions src/main/java/com/xkcoding/http/HttpUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,21 @@ public class HttpUtil {

static {
Http defaultProxy = null;
ClassLoader classLoader = HttpUtil.class.getClassLoader();
// java 11 HttpClient
if (ClassUtil.isPresent("java.net.http.HttpClient", classLoader)) {
defaultProxy = new com.xkcoding.http.support.java11.HttpClientImpl();
}
// 基于 okhttp3
if (ClassUtil.isPresent("okhttp3.OkHttpClient", HttpUtil.class.getClassLoader())) {
if (ClassUtil.isPresent("okhttp3.OkHttpClient", classLoader)) {
defaultProxy = new OkHttp3Impl();
}
// 基于 httpclient
else if (ClassUtil.isPresent("org.apache.http.impl.client.HttpClients", HttpUtil.class.getClassLoader())) {
else if (ClassUtil.isPresent("org.apache.http.impl.client.HttpClients", classLoader)) {
defaultProxy = new HttpClientImpl();
}
// 基于 hutool
else if (ClassUtil.isPresent("cn.hutool.http.HttpRequest", HttpUtil.class.getClassLoader())) {
else if (ClassUtil.isPresent("cn.hutool.http.HttpRequest", classLoader)) {
defaultProxy = new HutoolImpl();
}
proxy = defaultProxy;
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/com/xkcoding/http/constants/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ public interface Constants {
*/
String CONTENT_TYPE_JSON = "application/json; charset=utf-8";

/**
* Content-Type
*/
String CONTENT_TYPE = "Content-Type";

/**
* Content-Encoding
*/
String CONTENT_ENCODING = "Content-Encoding";

/**
* 空字符串
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ public HttpClientImpl() {
this.httpClient = HttpClients.createDefault();
}

public HttpClientImpl(CloseableHttpClient httpClient) {
this.httpClient = httpClient;
}

private String exec(HttpRequestBase request) {
// 设置超时时长
request.setConfig(RequestConfig.custom()
Expand Down
188 changes: 188 additions & 0 deletions src/main/java/com/xkcoding/http/support/java11/HttpClientImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
/*
* Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & www.dreamlu.net).
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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 com.xkcoding.http.support.java11;

import com.xkcoding.http.constants.Constants;
import com.xkcoding.http.support.Http;
import com.xkcoding.http.support.HttpHeader;
import com.xkcoding.http.util.MapUtil;
import com.xkcoding.http.util.StringUtil;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;

/**
* java 11 HttpClient
*
* @author L.cm
*/
public class HttpClientImpl implements Http {
private final HttpClient client;

public HttpClientImpl() {
this(HttpClient.newBuilder().connectTimeout(Duration.ofMillis(Constants.TIMEOUT)).build());
}

public HttpClientImpl(HttpClient client) {
this.client = client;
}

private String exec(HttpRequest request) {
try {
return client.send(request, HttpResponse.BodyHandlers.ofString()).body();
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}

/**
* GET 请求
*
* @param url URL
* @return 结果
*/
@Override
public String get(String url) {
return this.get(url, null, false);
}

/**
* GET 请求
*
* @param url URL
* @param params 参数
* @param encode 是否需要 url encode
* @return 结果
*/
@Override
public String get(String url, Map<String, String> params, boolean encode) {
return this.get(url, params, null, encode);
}

/**
* GET 请求
*
* @param url URL
* @param params 参数
* @param header 请求头
* @param encode 是否需要 url encode
* @return 结果
*/
@Override
public String get(String url, Map<String, String> params, HttpHeader header, boolean encode) {
String baseUrl = StringUtil.appendIfNotContain(url, "?", "&");
String reqUrl = baseUrl + MapUtil.parseMapToString(params, encode);

HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(reqUrl))
.GET()
.timeout(Duration.ofMillis(Constants.TIMEOUT));

if (header != null) {
MapUtil.forEach(header.getHeaders(), builder::header);
}

return exec(builder.build());
}

/**
* POST 请求
*
* @param url URL
* @return 结果
*/
@Override
public String post(String url) {
return this.post(url, null);
}

/**
* POST 请求
*
* @param url URL
* @param data JSON 参数
* @return 结果
*/
@Override
public String post(String url, String data) {
return this.post(url, data, null);
}

/**
* POST 请求
*
* @param url URL
* @param data JSON 参数
* @param header 请求头
* @return 结果
*/
@Override
public String post(String url, String data, HttpHeader header) {
HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(url))
.POST(HttpRequest.BodyPublishers.noBody())
.timeout(Duration.ofMillis(Constants.TIMEOUT));

if (StringUtil.isNotEmpty(data)) {
builder.POST(HttpRequest.BodyPublishers.ofString(data, Constants.DEFAULT_ENCODING));
builder.header(Constants.CONTENT_ENCODING, Constants.DEFAULT_ENCODING.displayName());
builder.header(Constants.CONTENT_TYPE, Constants.CONTENT_TYPE_JSON);
} else {
builder.POST(HttpRequest.BodyPublishers.noBody());
}

if (header != null) {
MapUtil.forEach(header.getHeaders(), builder::header);
}

return this.exec(builder.build());
}

/**
* POST 请求
*
* @param url URL
* @param params form 参数
* @param encode 是否需要 url encode
* @return 结果
*/
@Override
public String post(String url, Map<String, String> params, boolean encode) {
return this.post(url, params, null, encode);
}

/**
* POST 请求
*
* @param url URL
* @param params form 参数
* @param header 请求头
* @param encode 是否需要 url encode
* @return 结果
*/
@Override
public String post(String url, Map<String, String> params, HttpHeader header, boolean encode) {
String baseUrl = StringUtil.appendIfNotContain(url, "?", "&");
String reqUrl = baseUrl + MapUtil.parseMapToString(params, encode);
return this.post(reqUrl, null, header);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,17 @@ public class OkHttp3Impl implements Http {
private final OkHttpClient httpClient;
public static final MediaType CONTENT_TYPE_JSON = MediaType.get(Constants.CONTENT_TYPE_JSON);


public OkHttp3Impl() {
this.httpClient = new OkHttpClient().newBuilder()
this(new OkHttpClient().newBuilder()
.connectTimeout(Duration.ofMillis(Constants.TIMEOUT))
.writeTimeout(Duration.ofMillis(Constants.TIMEOUT))
.readTimeout(Duration.ofMillis(Constants.TIMEOUT))
.build();
.build());
}

public OkHttp3Impl(OkHttpClient httpClient) {
this.httpClient = httpClient;
}

private String exec(Request request) {
Expand Down
24 changes: 24 additions & 0 deletions src/main/java11/java.net.http/HttpClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package java.net.http;

import java.io.IOException;
import java.time.Duration;

/**
* For the Java 8 compatibility when compiled with JDK 11+.
*
* @author L.cm
*/
public abstract class HttpClient {

public static HttpClient.Builder newBuilder() {
return null;
}

public abstract <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler) throws IOException, InterruptedException;

public interface Builder {
Builder connectTimeout(Duration duration);

HttpClient build();
}
}
Loading