Android-2 Kotlin Retrofit

上篇文章使用了EventBusVolley實現了網絡請求和組件間的通訊,今天,我們通過另一種方式來實現,即RxAndroidRetrofit,我是實用主義者,RxAdnroid原理這些,還有RxAndoridEventBus的區別和比較,以及VolleyRetrofit的選擇,網上有很多的文章和建議,我這里就不復述了,因為我覺得我沒有那些作者理解的透徹,我就不去誤導了,我們還是直接上代碼來的實際點:

開發語言: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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容