目前,主要的安卓网络框架有okhttp,retrofit,android-async-http,volley。其中,retrofit底层基于okhttp来实现,内部对OkHtttp客户端做了封装。
首先,Retrofit使用注解方式,简化了我们的URL拼写形式,而且注解含义一目了然,简单易懂;
其次,Retrofit使用简单,结构层次分明,每一步都能清晰的表达出之所以要使用的寓意;
再者,Retrofit支持同步和异步执行,使得请求变得简单,只要调用enqueue/execute即可完成;
最后,Retrofit更大自由度的支持我们自定义的业务逻辑,如自定义Converters。
1. 添加依赖库
implementation'com.squareup.retrofit2:retrofit:2.4.0'
implementation deps.retrofit.runtime
implementation deps.retrofit.gson
implementation deps.retrofit.rxjava_adapter
implementation deps.okhttp_logging_interceptor
2. 请求网络
val loading = DialogHelper.loading(this)
NetApi.getMyGoods("1", "1", "1", "20")
.compose(RxHelper.applyLoading(loading))
.subscribe({ res->
handleData(res.data!!)
})
3. 处理返回数据
private fun handleData(data: MyGoodsListModel) {
}
4. 写getMyGoods的api参数
fun getMyGoods(pocCustId: String, orderStatus: String, pageNum: String, pageSize: String): Flowable> {
val map =hashMapOf(Pair("pocCustId", pocCustId), Pair("orderStatus", orderStatus), Pair("pageNum", pageNum), Pair("pageSize", pageSize))
return CdamService.api
.getMyGoodslist(map)
.compose(apply())
}
5. 写RxHelper
object RxHelper {
fun applyLoading(loading: Dialog): FlowableTransformer {
return FlowableTransformer { flowable->
flowable.doOnSubscribe{ loading.show()}
.doFinally{ loading.dismiss()}
}
}
}
6.写CdamService层
object CdamService {
val api: CdamApiby lazy {
val parameterInterceptor= CommonParamsInterceptor()
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(parameterInterceptor)
.addInterceptor(HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY))
.readTimeout(5, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.build()
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(API_BASE_URL)
.client(okHttpClient)
.build()
return@lazy retrofit.create(CdamApi::class.java)
}
private val API_BASE_URL = BuildConfig.SERVICE_PLATFORM
private fun addParameters(builder: HttpUrl.Builder, params: Map): HttpUrl.Builder {
for ((key, value)in params) {
builder.addQueryParameter(key, value)
}
return builder
}
private fun getToken(): String {
return "81b78ff7-b7c6-4b43-b1da-7f738af5dd36"
}
}
7.写uri注入层
@POST("order/order/queryMyProductList")
fun getMyGoodslist(@Body loginRequest: Map
): Flowable>
8.写参数model层
data class MyGoodsListModel(val currentPage: String,
val totalPage: String,
val records: List?
) : Serializable
完成使用retrofit进行网络请求,并对结果进行处理的操作。