Using Kotlin to write basic network requests

Posted by deolsabh on Wed, 18 Dec 2019 18:35:07 +0100

The source download link has been given at the end of the article

First, add the dependency required by the network request to 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"

Second, we take the api of visiting github as an example to request the network:

  • Create a data class (with the help of JsonToKotlinClass.jar, a link to the jar package will be provided at the end of the article)
    kotlin will help us create get () method by default. If we want to create getter and setter methods at the same time, we need to change the keyword val to 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
)

III. create Api

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

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

Four: next is the code we want to access the network request:

  • Create 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)

  • Use the default access method of Retrofit, and do not introduce 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()//Get request data entity
                        println(userInfoEntity.toString())//Print request results
                    }
                })
  • Access using Rxjava
api.getFollowers()
                .subscribeOn(Schedulers.io())//Switch io thread request network
                .unsubscribeOn(AndroidSchedulers.mainThread())//Switch to ui main thread update ui
                .subscribe({ result ->//Request result
                    println(result.toString())
                }, { error ->//Request error
                    println(error.message)
                }, {//Request completed
                    println("complete")
                })

Source download address
jsonToKotlin, similar to GsonFormart in Java

Topics: Retrofit network github Java