第一次写博客,感觉还是有点的小激动。
主要对自己开始学习Kotlin的过程做个记录,毕竟好记性不如烂笔头。虽然我一直都没有做到,这可能是个开始。
依赖的添加:
implementation 'com.squareup.okhttp3:okhttp:3.1.2'
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.60'
// 这里有一个大坑啊。fastjson版本不是1.2.36和1.1.61是不支持Kotlin的。希望官网是早日更新
implementation 'com.alibaba:fastjson:1.2.36'
implementation 'com.alibaba:fastjson:1.1.61.android'
首先是对okhttp的封装
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit
class HttpManager private constructor() {
var httpClient: OkHttpClient? = null
val timeUnit: TimeUnit = TimeUnit.SECONDS
val connectTimeOut: Long = 10
val readTimeOut: Long = 10
val writeTimeOut: Long = 10
var interceptors: ArrayList<Interceptor> = ArrayList()
var networkInterceptors: ArrayList<Interceptor> = ArrayList()
companion object {
fun instace() = Holder.INSTACE
}
private object Holder {
val INSTACE = HttpManager()
init {
INSTACE.initHttpClient()
}
}
fun initHttpClient(): OkHttpClient? {
var builder = OkHttpClient.Builder()
.connectTimeout(connectTimeOut, timeUnit)
.readTimeout(readTimeOut, timeUnit)
.writeTimeout(writeTimeOut, timeUnit)
builder = initInterceptor(builder, interceptors)
builder = initNetworkInterceptor(builder, networkInterceptors)
httpClient = builder.build()
return httpClient
}
fun addInterceptor(interceptors: ArrayList<Interceptor>) {
this.interceptors = interceptors
}
fun addNetworkInterceptor(interceptors: ArrayList<Interceptor>) {
this.networkInterceptors = interceptors
}
fun initInterceptor(builder: OkHttpClient.Builder?, interceptors: