1. 程式人生 > >使用Kotlin編寫網路基本網路請求

使用Kotlin編寫網路基本網路請求

原始碼下載連結已經在篇尾給出

一:首先將網路請求需要的依賴新增到build.gradle中:

    //Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    implementation "com.squareup.retrofit2:adapter-rxjava2:2.4.0"
    //RxJava
    implementation "io.reactivex.rxjava2:rxjava:2.2.0"
    //RxAndroid
    implementation "io.reactivex.rxjava2:rxandroid:2.0.2"

二:我們以訪問github的api為例,請求網路:

  • 建立資料類(這裡藉助JsonToKotlinClass.jar,在篇尾會給出該jar包的連結) kotlin會預設幫我們建立好get()方法,如果想同時建立 getter 和 setter 方法需要將關鍵字val 更改為 var。

data class UserInfoEntity(
    val login: String,
    val id: Int,
    val node_id: String,
    val avatar_url: String,
    val gravatar_id: String,
    val url: String,
    val html_url: String,
    val followers_url: String,
    val following_url: String,
    val gists_url: String,
    val starred_url: String,
    val subscriptions_url: String,
    val organizations_url: String,
    val repos_url: String,
    val events_url: String,
    val received_events_url: String,
    val type: String,
    val site_admin: Boolean,
    val name: Any,
    val company: Any,
    val blog: String,
    val location: Any,
    val email: Any,
    val hireable: Any,
    val bio: Any,
    val public_repos: Int,
    val public_gists: Int,
    val followers: Int,
    val following: Int,
    val created_at: String,
    val updated_at: String
)

data class FollowersEntity(
    val login: String,
    val id: Int,
    val node_id: String,
    val avatar_url: String,
    val gravatar_id: String,
    val url: String,
    val html_url: String,
    val followers_url: String,
    val following_url: String,
    val gists_url: String,
    val starred_url: String,
    val subscriptions_url: String,
    val organizations_url: String,
    val repos_url: String,
    val events_url: String,
    val received_events_url: String,
    val type: String,
    val site_admin: Boolean
)

三:建立Api


interface Api {
    @GET("users/{path}")
    fun getUserInfo(@Path("path") string: String): Call<UserInfoEntity>

    @GET("users/HexlDL/followers")
    fun getFollowers():Observable<List<FollowersEntity>>
}

四:接下來就是我們要訪問網路請求的程式碼:

  • 建立Retrofit
	    val baseUrl: String = "https://api.github.com/"
        val retrofit = Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        val api = retrofit.create(Api::class.java)

  • 使用Retrofit預設訪問方式,不引入Rxjava
api.getUserInfo("HexlDL")
                .enqueue(object : Callback<UserInfoEntity> {
                    override fun onFailure(call: Call<UserInfoEntity>?, t: Throwable?) {
                        println(t?.localizedMessage)
                    }

                    override fun onResponse(call: Call<UserInfoEntity>?, response: Response<UserInfoEntity>?) {
                        val userInfoEntity = response?.body()//獲取請求資料實體
                        println(userInfoEntity.toString())//列印請求結果
                    }
                })
  • 使用Rxjava訪問
api.getFollowers()
                .subscribeOn(Schedulers.io())//切換io執行緒請求網路
                .unsubscribeOn(AndroidSchedulers.mainThread())//切換到ui主執行緒更新ui
                .subscribe({ result ->//請求結果
                    println(result.toString())
                }, { error ->//請求錯誤
                    println(error.message)
                }, {//請求完成
                    println("complete")
                })