项目封装库系列之“四”,网络库(Retrofit 2.0 )

引言:记录自己项目中使用的库,非技术文章。

1、集成retrofit 等库;

 implementation 'com.squareup.retrofit2:retrofit:2.3.0'
 implementation 'com.squareup.retrofit2:converter-gson:2.3.0' //json转换
 implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'//String 类型转换

1.1、项目结构预览

2. 初始化Retrofit 及定义回调。

NetBase.kt 如下:

/**
 *  * @author zhaobin
 */
private val retrofit = Retrofit.Builder().apply {
    client(OkHttpClient())
    baseUrl("http://xxxxxxxx/")
        //添加全局header
        .client(
            OkHttpClient()
                .newBuilder()
                .addInterceptor(RequestInterceptor())
                .build()
        )
    addConverterFactory(ScalarsConverterFactory.create())
    addConverterFactory(GsonConverterFactory.create())
}.build()

val connectService = retrofit.create(ConnectService::class.java)

回调封装 (高阶函数、主要用于简化回调结构):

/**
 * 基础回调封装
 * 采用高阶函数 进行函数回调处理!
 * @author zhaobin
 */
class BaseCallBack<T> : Callback<T> {

    private lateinit var success: (data: T?) -> Unit

    private lateinit var fail: (t: Throwable) -> Unit

    fun onResponseResult(success: (data: T?) -> Unit) {
        this.success = success
    }

    fun onFailureResult(fail: (t: Throwable) -> Unit) {
        this.fail = fail
    }


    override fun onResponse(call: Call<T>, response: Response<T>) {
        if (response.isSuccessful) {
            //或者 success(response.body())
            success.invoke(response.body())
        }
    }

    override fun onFailure(call: Call<T>, t: Throwable) {
        fail.invoke(t)
    }
}

扩展Retrofit中的Call(回调)

RetrofitExpand.kt

/**
 * 简化回调 异步
 *  * @author zhaobin
 */
fun <T> Call<T>.requestAsync(call: BaseCallBack<T>.() -> Unit) {
    //实例化回调对象
    val callBack = BaseCallBack<T>()
    //高阶函数回调赋值 、个人理解 callBack 赋值给call
    callBack.call()
    this.enqueue(callBack)
}

3、定义测试类及接口:

StartDataBean.kt 测试类 (不要关心类的内容,可以定义简单的测试类)

//test
data class StartDataBean(
    val games: List<GameInfo>?,
    val specificUserConfig: SpecificUserConfig?,
    val specificUsers: List<SpecificUsers>?,
    val hotTeamIds: List<String>?
)

data class GameInfo(
    val gameId: String?,
    val gameName: String?,
    val icon: String?,
    val url: String?
)

data class SpecificUserConfig(
    val qixiaogongUserId: String?,
    val qixiaogouUserId: String?,
    val qixiaoleUserId: String?
)

data class SpecificUsers(val tag: String?, val userId: String?)

 接口定义 

/**
 *  * @author zhaobin
 */
interface ConnectService {

    @POST("app/start/data")
    fun startAppInfo(): Call<StartDataBean>
}

4.发起网络请求

/**
 *  * @author zhaobin
 *  retrofit2
 */
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        //发起请求
        connectService.startAppInfo().requestAsync {
            onResponseResult {
                Log.d("xxxxxxxxxx","result  $it")
                findViewById<TextView>(R.id.tv).text = it.toString()
            }
            onFailureResult {
                Log.d("xxxxxxxxxx","params it")
            }
        }
    }
}

last:全局Header的添加(根据自己需求 是否添加)。

/**
 * 添加全局头部信息
 */
class RequestInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest = chain.request()
        val nowRequest = oldRequest.newBuilder()
            .headers(Headers.of(getHeaders()))
            .build()
        return chain.proceed(nowRequest)
    }

    //test 添加全局header
    private fun getHeaders() =
        mutableMapOf("android" to "android", "version" to "110")
}

 总结:请求很简单、但回调很啰嗦.... 没办法捏!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值