《Kotlin系列》之协程搭配Retrofit+OkHttp3网络请求封装(kotlin+retrofit+okhttp3)

本文介绍了如何使用Kotlin、Retrofit和OkHttp封装网络框架,涉及协程、异常处理及MVVM架构。通过单例管理RetrofitClient,实现BaseUrl的动态切换,并提供了网络请求的基类封装,简化了 ViewModel 中的网络调用。同时展示了在协程中如何发起网络请求,避免手动处理线程。整个封装旨在提高代码的可维护性和简洁性。

上一篇:《Kotlin系列》之MVVM架构封装

前言

上一篇关于MVVM 架构的基类封装,这篇会在MVVM 的基础上示范使用 kotlin+retrofit+okhttp 封装的网络框架,里面会涉及到协程的使用,
协程异常处理包装。

导入相关包

kotlin 相关配置见上一篇,这里主要是Retrofit 和okHttp3 的包

    api 'com.squareup.okhttp3:logging-interceptor:3.6.0'
    api 'com.squareup.retrofit2:adapter-rxjava2:2.6.0'
    api 'com.squareup.retrofit2:adapter-rxjava:2.6.0'
    api 'com.squareup.okhttp3:okhttp:3.12.0'
    api 'com.squareup.retrofit2:retrofit:2.6.0'
    api 'com.squareup.retrofit2:converter-gson:2.6.0'
    api 'com.squareup.retrofit2:adapter-rxjava2:2.6.0'

封装

先看看图中基本的结构
在这里插入图片描述

  • RetrofitClient: client 管理类
    这里是整个业务封装的核心,其中包括https 证书校验、baseUrl 切换
class RetrofitClient {
   
   

    /**
     * retrofit 初始化build
     */
    private fun RetrofitClient() {
   
   }


   //做成单例
    companion object {
   
   
        private var retrofitClient: RetrofitClient? = null
        private const val DEFAULT_TIME_OUT = 15
        private val sRetrofitManager: MutableMap<Int, Retrofit> = HashMap()
        fun getInstance(): RetrofitClient {
   
   
            if (retrofitClient == null) {
   
   
                synchronized(RetrofitClient::class.java) {
   
   
                    retrofitClient = RetrofitClient()
                    return retrofitClient as RetrofitClient
                }
            }
            return retrofitClient as RetrofitClient
        }
    }


    /**
     * 创建连接客户端
     */
    private fun createOkHttpClient(): OkHttpClient {
   
   

        //设置请求头拦截器
        //设置日志拦截器
        val httpLoggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT)
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY


        //根据需求添加不同的拦截器

        return OkHttpClient.Builder()
            .connectTimeout(DEFAULT_TIME_OUT.toLong(), TimeUnit.SECONDS)
            .writeTimeout(DEFAULT_TIME_OUT.toLong(), TimeUnit.SECONDS)
            .readTimeout(DEFAULT_TIME_OUT.toLong(), TimeUnit.SECONDS)
            .connectionPool(ConnectionPool(8, 10, TimeUnit.SECONDS)) //添加这两行代码
            .sslSocketFactory(TrustAllCerts.createSSLSocketFactory()!!, TrustAllCerts())
            .hostnameVerifier(TrustAllCerts.TrustAllHostnameVerifier())
            .addInterceptor(httpLoggingInterceptor)
            .build()
    }


    /**
     * 根据host 类型判断是否需要重新创建Client,因为一个app 有不同的BaseUrl,切换BaseUrl 就需要重新创建Client
     * 所以,就根据类型来从map中取出对应的client
     */
    fun <T> getDefault(interfaceServer: Class<T>?, hostType: Int): T {
   
   
        val retrofitManager = sRetrofitManager[hostType]
        return if (retrofitManager == null) {
   
   
            create(interfaceServer, hostType)
        } else retrofitManager.create(interfaceServer!!)
    }


    /**
     *
     */
    private fun <T> create(interfaceServer: Class<T>?
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值