Kotlin okhttp 简单封装

第一次写博客,感觉还是有点的小激动。 主要对自己开始学习Kotlin的过程做个记录,毕竟好记性不如烂笔头。虽然我一直都没有做到,这可能是个开始。 依赖的添加: implementation 'com.squareup.okhttp3:okhttp:3.1.2' implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.60...
摘要由CSDN通过智能技术生成

第一次写博客,感觉还是有点的小激动。
主要对自己开始学习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: 
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值