上篇文章使用了EventBus和Volley实现了网络请求和组件间的通讯,今天,我们通过另一种方式来实现,即RxAndroid和Retrofit,我是实用主义者,RxAdnroid原理这些,还有RxAndorid和EventBus的区别和比较,以及Volley和Retrofit的选择,网上有很多的文章和建议,我这里就不复述了,因为我觉得我没有那些作者理解的透彻,我就不去误导了,我们还是直接上代码来的实际点:
开发语言:Kotlin
开源框架:RxAndroid Retrofit
Retrofit封装
主要是对RetrofitError进行了部分处理,详见代码:
RetrofitExtensions.kt
package com.vslimit.kotlindemo.util.net.retrofit
import android.content.res.Resources
import com.vslimit.kotlindemo.R
import retrofit.RetrofitError
/**
* Created by vslimit on 16/11/30.
*/
fun RetrofitError.toString(res: Resources): String {
when (kind) {
RetrofitError.Kind.HTTP -> return getApiErrorMessage(res)
RetrofitError.Kind.NETWORK -> return res.getString(R.string.generic_server_down)
RetrofitError.Kind.CONVERSION -> return res.getString(R.string.no_data_connection)
RetrofitError.Kind.UNEXPECTED -> return res.getString(R.string.generic_error)
else -> return res.getString(R.string.generic_error)
}
}
private fun RetrofitError.getApiErrorMessage(res: Resources): String {
if (response != null) {
when (response.status) {
404 -> return res.getString(R.string.no_results_found)
422, 401, 411, 417 -> {
return res.getString(R.string.generic_error)
}
else -> return res.getString(R.string.generic_server_down)
}
}
return res.getString(R.string.generic_error)
}
Retrofit实现Http请求
ServiceFactory
package com.vslimit.kotlindemo.service
import retrofit.RestAdapter
/**
* Created by vslimit on 16/7/22.
*/
object ServiceFactory {
fun <T> createRetrofitService(clazz: Class<T>, endPoint: String): T {
return RestAdapter.Builder().setEndpoint(endPoint).build().create(clazz)
}
}
RestfulService
package com.vslimit.kotlindemo.service
import com.vslimit.kotlindemo.model.IPResult
import retrofit.http.*
import rx.Observable
/**
* Created by vslimit on 16/7/22.
*/
package com.vslimit.kotlindemo.service
import com.vslimit.kotlindemo.model.IPResult
import retrofit.http.*
import rx.Observable
/**
* Created by vslimit on 16/7/22.
*/
interface RestfulService {
/**
* post请求实现样例代码,非可用
*/
@FormUrlEncoded
@POST("/login")
fun login(@Field("q") q: String): Observable<IPResult>
/**
* get请求代码,可用
*/
@GET("/getIpInfo.php")
fun getIpInfo(@Query("ip") ip: String): Observable<IPResult>
companion object {
val SERVICE_ENDPOINT = "http://ip.taobao.com/service"
}
}
项目中使用
private fun init() {
toast("正在加载中...")
val service = ServiceFactory.createRetrofitService(RestfulService::class.java, RestfulService.SERVICE_ENDPOINT)
service.getIpInfo("63.223.108.42").subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(object : Subscriber<IPResult>() {
override fun onCompleted() {
toast("加载完成!!!")
}
override fun onError(e: Throwable) {
toast(if (e is RetrofitError) e.toString(resources) else e.toString())
}
override fun onNext(result: IPResult) {
resultTv.text = result.data!!.country
}
})
}
至此,完成了对Retrofit使用,项目中增加新的接口调用时,在RestfulService中添加新的请求接口即可。
所有demo代码已提交更新,详见:https://github.com/vslimit/kotlindemo