最近項(xiàng)目需要使用 Java 重度調(diào)用 HTTP API 接口,于是想著封裝一個(gè)團(tuán)隊(duì)公用的 HTTP client lib. 這個(gè)庫需要支持以下特性:
連接池管理逾礁,包括連接創(chuàng)建和超時(shí)盅称、空閑連接數(shù)控制蜗顽、每個(gè) host 的連接數(shù)配置等萍膛⊙榘茫基本上擅羞,我們想要一個(gè) go HTTP 標(biāo)準(zhǔn)庫自帶的連接吃管理功能。
域名解析控制鲁森。因?yàn)檎{(diào)用量會比較大祟滴,因此希望在域名解析這一層做一個(gè)調(diào)用端可控的負(fù)載均衡,同時(shí)可以對每個(gè)服務(wù)器 IP 進(jìn)行失敗率統(tǒng)計(jì)和健康度檢查歌溉。
Form/JSON 調(diào)用支持良好垄懂。
支持同步和異步調(diào)用。
在 Java 生態(tài)中痛垛,雖然有數(shù)不清的 HTTP client lib 組件庫草慧,但是大體可以分為這三類:
JDK 自帶的 HttpURLConnection 標(biāo)準(zhǔn)庫;
Apache HttpComponents HttpClient, 以及基于該庫的 wrapper, 如 Unirest.
非基于 Apache HttpComponents HttpClient匙头, 大量重寫應(yīng)用層代碼的 HTTP client 組件庫漫谷,典型代表是 OkHttp.
HttpURLConnection
使用 HttpURLConnection 發(fā)起 HTTP 請求最大的優(yōu)點(diǎn)是不需要引入額外的依賴,但是使用起來非常繁瑣蹂析,也缺乏連接池管理舔示、域名機(jī)械控制等特性支持碟婆。以發(fā)起一個(gè) HTTP POST 請求為例:
import?java.io.BufferedReader;
import?java.io.InputStream;
import?java.io.InputStreamReader;
import?java.io.OutputStream;
import?java.net.HttpURLConnection;
import?java.net.URL;
public?class?HttpUrlConnectionDemo {
public?static?void?main(String[] args)?throws?Exception {
String urlString = "https://httpbin.org/post";
String bodyString = "password=e10adc3949ba59abbe56e057f20f883e&username=test3";
URL url =?new?URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(bodyString.getBytes("utf-8"));
os.flush();
os.close();
if?(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
BufferedReader reader =?new?BufferedReader(new?InputStreamReader(is));
StringBuilder sb =?new?StringBuilder();
String line;
while?((line = reader.readLine()) !=?null) {
sb.append(line);
}
System.out.println("rsp:" + sb.toString());
}?else?{
System.out.println("rsp code:" + conn.getResponseCode());
}
}
}
可以看到,使用 HttpURLConnection 發(fā)起 HTTP 請求是比較原始(low level)的惕稻,基本上你可以理解為它就是對網(wǎng)絡(luò)棧傳輸層(HTTP 一般為 TCP竖共,HTTP over QUIC 是 UDP)進(jìn)行了一次淺層次的封裝,操作原語就是在打開的連接上面寫請求 request 與讀響應(yīng) response. 而且 HttpURLConnection 無法支持 HTTP/2. 顯然,官方是知道這些問題的俺祠,因此在 Java 9 中公给,官方在標(biāo)準(zhǔn)庫中引入了一個(gè) high level、支持 HTTP/2 的 HttpClient. 這個(gè)庫的接口封裝就非常主流到位了蜘渣,發(fā)起一個(gè)簡單的 POST 請求:
HttpRequest request = HttpRequest.newBuilder()
.uri(new?URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyProcessor.fromString("Sample request body"))
.build();
封裝的最大特點(diǎn)是鏈?zhǔn)秸{(diào)用非常順滑淌铐,支持連接管理等特性。但是這個(gè)庫只能在 Java 9 及以后的版本使用蔫缸,Java 9 和 Java 10 并不是 LTS 維護(hù)版本腿准,而接下來的 Java 11 LTS 要在2018.09.25發(fā)布,應(yīng)用到線上還需要等待一段時(shí)間拾碌。因此释涛,雖然挺喜歡這個(gè)自帶標(biāo)準(zhǔn)庫(畢竟可以不引入三方依賴),但當(dāng)前是無法在生產(chǎn)環(huán)境使用的倦沧。
Apache HttpComponents HttpClient
Apache HttpComponents HttpClient 的前身是 Apache Commons HttpClient, 但是 Apache Commons HttpClient 已經(jīng)停止開發(fā),如果你還在使用它它匕,請切換到 Apache HttpComponents HttpClient 上來展融。
Apache HttpComponents HttpClient 支持的特性非常豐富,完全覆蓋我們的需求豫柬,使用起來也非常順手:
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.impl.client.HttpClients;
public class HttpComponentsDemo {
final static CloseableHttpClient client = HttpClients.createDefault();
// 常規(guī)調(diào)用
private String sendPostForm(String url, Map<String, String> params) throws Exception {
HttpPost request = new HttpPost(url);
// set header
request.setHeader("X-Http-Demo", HttpComponentsDemo.class.getSimpleName());
// set params
if (params != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity bodyEntity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
//System.out.println("body:" + IOUtils.toString(bodyEntity.getContent()));
request.setEntity(new UrlEncodedFormEntity(nameValuePairList));
}
// send request
CloseableHttpResponse response = client.execute(request);
// read rsp code
System.out.println("rsp code:" + response.getStatusLine().getStatusCode());
// return content
String ret = readResponseContent(response.getEntity().getContent());
response.close();
return ret;
}
// fluent 鏈?zhǔn)秸{(diào)用
private String sendGet(String url) throws Exception {
return Request.Get(url)
.connectTimeout(1000)
.socketTimeout(1000)
.execute().returnContent().asString();
}
private String readResponseContent(InputStream inputStream) throws Exception {
if (inputStream == null) {
return "";
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int len;
while (inputStream.available() > 0) {
len = inputStream.read(buf);
out.write(buf, 0, len);
}
return out.toString();
}
public static void main(String[] args) throws Exception {
HttpComponentsDemo httpUrlConnectionDemo = new HttpComponentsDemo();
String url = "https://httpbin.org/post";
Map<String, String> params = new HashMap<String, String>();
params.put("foo", "bar中文");
String rsp = httpUrlConnectionDemo.sendPostForm(url, params);
System.out.println("http post rsp:" + rsp);
url = "https://httpbin.org/get";
System.out.println("http get rsp:" + httpUrlConnectionDemo.sendGet(url));
}
}
對 Client 細(xì)致的配置和自定義支持也是非常到位的:
// Create a connection manager with custom configuration.
PoolingHttpClientConnectionManager connManager =?newPoolingHttpClientConnectionManager(
socketFactoryRegistry, connFactory, dnsResolver);
// Create socket configuration
SocketConfig socketConfig = SocketConfig.custom()
.setTcpNoDelay(true)
.build();
// Configure the connection manager to use socket configuration either
// by default or for a specific host.
connManager.setDefaultSocketConfig(socketConfig);
connManager.setSocketConfig(new?HttpHost("somehost", 80), socketConfig);
// Validate connections after 1 sec of inactivity
connManager.setValidateAfterInactivity(1000);
// Create message constraints
MessageConstraints messageConstraints = MessageConstraints.custom()
.setMaxHeaderCount(200)
.setMaxLineLength(2000)
.build();
// Create connection configuration
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE)
.setCharset(Consts.UTF_8)
.setMessageConstraints(messageConstraints)
.build();
// Configure the connection manager to use connection configuration either
// by default or for a specific host.
connManager.setDefaultConnectionConfig(connectionConfig);
connManager.setConnectionConfig(new?HttpHost("somehost", 80), ConnectionConfig.DEFAULT);
// Configure total max or per route limits for persistent connections
// that can be kept in the pool or leased by the connection manager.
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(10);
connManager.setMaxPerRoute(new?HttpRoute(new?HttpHost("somehost", 80)), 20);
基本上告希,在 Java 原生標(biāo)準(zhǔn)庫不給力的情況下,Apache HttpComponents HttpClient 是最佳的 HTTP Client library 選擇烧给。但這個(gè)庫當(dāng)前還不支持 HTTP/2燕偶,支持 HTTP/2 的版本還處于 beta 階段(2018.09.23),因此并不適合用于 Android APP 中使用础嫡。
OkHttp
由于當(dāng)前 Apache HttpComponents HttpClient 版本并不支持 HTTP/2, 而 HTTP/2 對于移動客戶端而言指么,無論是從握手延遲、響應(yīng)延遲榴鼎,還是資源開銷看都有相當(dāng)吸引力伯诬。因此這就給了高層次封裝且支持 HTTP/2 的 http client lib 足夠的生存空間。其中最典型的要數(shù)OkHttp.
import okhttp3.*;
import org.apache.http.util.CharsetUtils;
import java.util.HashMap;
import java.util.Map;
public class OkHttpDemo {
OkHttpClient client = new OkHttpClient();
private String sendPostForm(String url, final Map<String, String> params) throws Exception {
FormBody.Builder builder = new FormBody.Builder(CharsetUtils.get("UTF-8"));
if (params != null) {
for (Map.Entry<String, String> entry: params.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
}
RequestBody requestBody = builder.build();
Request request = new Request.Builder().url(url).post(requestBody).build();
return client.newCall(request).execute().body().string();
}
private String sendGet(String url) throws Exception {
Request request = new Request.Builder().url(url).build();
return client.newCall(request).execute().body().string();
}
public static void main(String[] args) throws Exception {
OkHttpDemo okHttpDemo = new OkHttpDemo();
String url = "https://httpbin.org/post";
Map<String, String> params = new HashMap<String, String>();
params.put("foo", "bar中文");
String rsp = okHttpDemo.sendPostForm(url, params);
System.out.println("http post rsp:" + rsp);
url = "https://httpbin.org/get";
System.out.println("http get rsp:" + okHttpDemo.sendGet(url));
}
}
OkHttp 接口設(shè)計(jì)友好巫财,支持 HTTP/2盗似,并且在弱網(wǎng)和無網(wǎng)環(huán)境下有自動檢測和恢復(fù)機(jī)制,因此平项,是當(dāng)前 Android APP 開發(fā)中使用最廣泛的 HTTP clilent lib 之一赫舒。
另一方面悍及,OkHttp 提供的接口與 Java 9 中 HttpClint 接口比較類似 (嚴(yán)格講,應(yīng)該是 Java 9 借鑒了 OkHttp 等開源庫的接口設(shè)計(jì)接癌?)心赶,因此,對于喜歡減少依賴扔涧,鐘情于原生標(biāo)準(zhǔn)庫的開發(fā)者來說园担,在 Java 11 中,從 OkHttp 切換到標(biāo)準(zhǔn)庫是相對容易的枯夜。因此弯汰,以 OkHttp 為代表的 http 庫以后的使用場景可能會被蠶食一部分。
小結(jié)
HttpURLConnection 封裝層次太低湖雹,并且支持特性太少咏闪,不建議在項(xiàng)目中使用。除非你的確不想引入第三方 HTTP 依賴(如減少包大小摔吏、目標(biāo)環(huán)境不提供三方庫支持等)鸽嫂。
Java 9 中引入的 HttpClient,封裝層次和支持特性都不錯(cuò)征讲。但是因?yàn)?Java 版本的原因据某,應(yīng)用場景還十分有限,建議觀望一段時(shí)間再考慮在線上使用诗箍。
如果你不需要 HTTP/2特性癣籽,Apache HttpComponents HttpClient 是你的最佳選擇,比如在服務(wù)器之間的 HTTP 調(diào)用滤祖。否則筷狼,請使用 OkHttp, 如 Android 開發(fā)。
歡迎工作一到五年的Java工程師朋友們加入Java架構(gòu)開發(fā): 854393687
群內(nèi)提供免費(fèi)的Java架構(gòu)學(xué)習(xí)資料(里面有高可用匠童、高并發(fā)埂材、高性能及分布式、Jvm性能調(diào)優(yōu)汤求、Spring源碼俏险,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多個(gè)知識點(diǎn)的架構(gòu)資料)合理利用自己每一分每一秒的時(shí)間來學(xué)習(xí)提升自己扬绪,不要再用"沒有時(shí)間“來掩飾自己思想上的懶惰寡喝!趁年輕,使勁拼勒奇,給未來的自己一個(gè)交代预鬓!