我愛(ài)說(shuō)實(shí)話,Mica-Http 超好用!
一、簡(jiǎn)介
mica-http 是基于 okhttp 的封裝,提供了 Fluent 語(yǔ)法的 http 工具包。mica-http 的語(yǔ)法簡(jiǎn)單易懂,同時(shí)還具有更好的性能和更高的安全性(自動(dòng)關(guān)閉資源)。另外 mica-http 帶有 http 請(qǐng)求日志打印功能,
二、快速上手
1.1 導(dǎo)入依賴
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>mica-http</artifactId>
<version>2.7.18.1</version>
</dependency>
1.2 快速開始
String html = HttpRequest.get("https://www.baidu.com")
.useConsoleLog() // 日志,同類有useSlf4jLog()和useLog(log::info),日志級(jí)別默認(rèn)為 BODY
.execute() // 執(zhí)行,這里并非正在執(zhí)行,這里只是轉(zhuǎn)換成了執(zhí)行對(duì)象
.asString(); // 真正行并轉(zhuǎn)換結(jié)果
System.out.println(html);
1.3 異步請(qǐng)求
// 發(fā)送異步請(qǐng)求
HttpRequest.delete("https://www.baidu.com")
.async() // 開啟異步
.onFailed((request, e) -> { // 異常時(shí)的處理
e.printStackTrace();
})
.onResponse(responseSpec -> { // 消費(fèi)響應(yīng), 注意:響應(yīng)的流只能讀一次
int httpCode = responseSpec.code();
})
.onSuccessful(responseSpec -> { // 消費(fèi)響應(yīng)成功 http code in [200..300)
// 注意:響應(yīng)結(jié)果流只能讀一次
JsonNode jsonNode = responseSpec.asJsonNode();
})
.execute(); // 異步最后發(fā)起請(qǐng)求
1.4 API說(shuō)明
// 同步請(qǐng)求 url,方法支持 get、post、patch、put、delete
HttpRequest.get("https://www.baidu.com/{param1}/{param2}")
// 使用 Slf4j 日志
.useSlf4jLog()
// url 路徑參數(shù)處理
.pathParam("param1", "abc1")
.pathParam("param2", "abc2")
// 添加 header
.addHeader("x-account-id", "mica001")
// 添加 cookie
.addCookie(builder -> builder.domain("www.baidu.com").name("name").value("value"))
// 設(shè)置 url 請(qǐng)求參數(shù),默認(rèn)進(jìn)行 url encode
.query("q", "mica")
.queryEncoded("name", "encodedValue")
// 對(duì)結(jié)果集進(jìn)行斷言重試
.retryOn(responseSpec -> !responseSpec.isOk())
// 設(shè)置代理
.proxy(InetSocketAddress.createUnresolved("127.0.0.1", 8080))
// 表單構(gòu)造器,同類 multipartFormBuilder 文件上傳表單構(gòu)造器
.formBuilder()
// 表單參數(shù)
.add("id", 123123)
// 發(fā)起請(qǐng)求
.execute()
// 結(jié)果集轉(zhuǎn)換,注:如果網(wǎng)絡(luò)異常等會(huì)直接拋出異常,當(dāng)然你還可以使用 onResponse、onSuccess 處理
.asJsonNode();
// 同類的方法有 asString、asBytes
// json 類響應(yīng):asJsonNode、asValue、asList、asMap、atJsonPath等,采用 jackson 處理
// file 文件:toFile
// 轉(zhuǎn)換成文件上傳的 Part:asPart 系列方法。
1.5 全局配置
全局日志配置:
// 設(shè)定全局日志級(jí)別 **NONE**(不打印日志)、 **BASIC**(只打印請(qǐng)求行和響應(yīng)行)、 **HEADERS**(在BASIC的基礎(chǔ)上打印出請(qǐng)求頭)、 **BODY**(在BASIC的基礎(chǔ)上打印出請(qǐng)求和響應(yīng)體)
HttpRequest.setGlobalLog(LogLevel.BODY);
// 設(shè)置控制臺(tái)日志,用于沒(méi)有日志依賴的 sdk 開發(fā)時(shí)使用
HttpRequest.setGlobalLog(HttpLogger.Console, LogLevel.BODY);
// 當(dāng)然你也可以設(shè)定為自己的 log,這樣就不用把 **net.dreamlu.mica.http** 包的日志設(shè)置為 info 級(jí)別。
HttpRequest.setGlobalLog(log::info);
自定義 OkHttpClient
OkHttpClient httpClient = new OkHttpClient.Builder()
.build();
HttpRequest.setHttpClient(httpClient);
1.6 Cookie管理
默認(rèn)內(nèi)置了 InMemoryCookieManager,會(huì)自動(dòng)保存和使用 cookie,另外可以自定義實(shí)現(xiàn) okhttp 的 CookieJar。
InMemoryCookieManager cookieManager = new InMemoryCookieManager();
HttpRequest.get("http://fast.dreamlu.net/api/auth/captcha")
.cookieManager(cookieManager)
.execute()
.asString();
三、性能優(yōu)異
http 壓測(cè)結(jié)果報(bào)告
第一輪
Benchmark Mode Cnt Score Error Units
MicaHttpBenchmark.micaHttp thrpt 5 899.299 ± 208.080 ops/min
MicaHttpBenchmark.okHttp thrpt 5 841.669 ± 106.094 ops/min
MicaHttpBenchmark.protoTypeOkHttp thrpt 5 346.647 ± 23.664 ops/min
第二輪
Benchmark Mode Cnt Score Error Units
MicaHttpBenchmark.micaHttp thrpt 5 876.651 ± 276.569 ops/min
MicaHttpBenchmark.okHttp thrpt 5 899.365 ± 194.188 ops/min
MicaHttpBenchmark.protoTypeOkHttp thrpt 5 341.028 ± 34.713 ops/min
第三輪
Benchmark Mode Cnt Score Error Units
MicaHttpBenchmark.micaHttp thrpt 5 944.017 ± 175.509 ops/min
MicaHttpBenchmark.okHttp thrpt 5 875.143 ± 164.594 ops/min
MicaHttpBenchmark.protoTypeOkHttp thrpt 5 331.370 ± 19.136 ops/min
解讀
- mica-http 對(duì) okhttp 進(jìn)行增強(qiáng)會(huì)復(fù)用OkHttpClient和連接池,并沒(méi)有明顯的性能損耗,偶爾結(jié)果還比 okhttp 表現(xiàn)得好。
- protoTypeOkHttp 采用的是每次 new OkHttpClient() 性能損耗明顯非常明顯,而且高并發(fā)下還有內(nèi)存泄露,所以大家在使用時(shí)一定要注意。
四、安全
mica-http 在執(zhí)行時(shí)會(huì)使用 try-with-resource語(yǔ)法自動(dòng)關(guān)流,所以在使用時(shí)不用擔(dān)心流關(guān)閉問(wèn)題。