引言:记录自己项目中使用的库,非技术文章。
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")
}
总结:请求很简单、但回调很啰嗦.... 没办法捏!