okhttp-extension 是针对 okhttp 3 增强的网络框架。使用 Kotlin 特性编写,提供便捷的 DSL 方式创建网络请求,支持协程、响应式编程等等。
其 core 模块只依赖 OkHttp,不会引入第三方库。
okhttp-extension 可以整合 Retrofit、Feign 框架,还提供了很多常用的拦截器。 另外,okhttp-extension 也给开发者提供一种新的选择。
github地址:https://github.com/fengzhizi715/okhttp-extension
1Features:
支持 DSL 创建 HTTP
GET
/POST
/PUT
/HEAD
/DELETE
/PATCH
requests.支持 Kotlin 协程
支持响应式(RxJava、Spring Reactor)
支持函数式
支持熔断器(Resilience4j)
支持异步请求的取消
支持 Request、Response 的拦截器
提供常用的拦截器
支持自定义线程池
支持整合 Retrofit、Feign 框架
支持 Websocket 的实现、自动重连等
core 模块只依赖 OkHttp,不依赖其他第三方库
Part1一. General
21.1 Basic
无需任何配置(零配置)即可直接使用,仅限于 Get 请求。
"https://baidu.com".httpGet().use {
println(it)
}
或者需要依赖协程,也仅限于 Get 请求。
"https://baidu.com".asyncGet()
.await()
.use {
println(it)
}
31.2 Config
配置 OkHttp 相关的参数以及拦截器,例如:
const val DEFAULT_CONN_TIMEOUT = 30
val loggingInterceptor by lazy {
LogManager.logProxy(object : LogProxy { // 必须要实现 LogProxy ,否则无法打印网络请求的 request 、response
override fun e(tag: String, msg: String) {
}
override fun w(tag: String, msg: String) {
}
override fun i(tag: String, msg: String) {
println("$tag:$msg")
}
override fun d(tag: String, msg: String) {
println("$tag:$msg")
}
})
LoggingInterceptor.Builder()
.loggable(true) // TODO: 发布到生产环境需要改成false
.request()
.requestTag("Request")
.response()
.responseTag("Response")
// .hideVerticalLine()// 隐藏竖线边框
.build()
}
val httpClient: HttpClient by lazy {
HttpClientBuilder()
.baseUrl("http://localhost:8080")
.allTimeouts(DEFAULT_CONN_TIMEOUT.toLong(), TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
.addInterceptor(CurlLoggingInterceptor())
.serializer(GsonSerializer())
.jsonConverter(GlobalRequestJSONConverter::class)
.build()
}
配置完之后,就可以直接使用 httpClient
httpClient.get{
url {
url = "/response-headers-queries"
"param1" to "value1"
"param2" to "value2"
}
header {
"key1" to "value1"
"key2" to "value2"
}
}.use {
println(it)
}
这里的 url 需要和 baseUrl 组成完整的 url。比如:http://localhost:8080/response-headers-queries 当然,也可以使用 customUrl 替代 baseUrl + url 作为完整的 url
41.3 AOP
针对所有 request、response 做一些类似 AOP 的行为。
需要在构造 httpClient 时,调用 addRequestProcessor()、addResponseProcessor() 方法,例如:
val httpClientWithAOP by lazy {
HttpClientBuilder()
.baseUrl("http://localhost:8080")
.allTimeouts(DEFAULT_CONN_TIMEOUT.toLong(), TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
.serializer(GsonSerializer())
.jsonConverter(GlobalRequestJSONConverter::class)
.addRequestProcessor { _, builder ->
println("request start")
builder
}
.addResponseProcessor {