Android kotlin Retrofit 之get請求

kotlin中Retrofit的基本使用之get

build.gradle中增加導入

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.2.2'
    implementation 'androidx.navigation:navigation-ui-ktx:2.2.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    //
    implementation 'io.reactivex.rxjava2:rxjava:2.1.4'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'

    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

}

1 創建網絡請求的接口

2 創建Retrofit實例

3 創建網絡請求接口的實例

4 發送網絡請求

interface GetApi {

    @GET("api/getUserInfo?")
    fun getUserInfo(@Query("id") userId: String?): Call<UserInfo?>?
}

data class UserInfo(val describe: String) {

}

//測試方法
  fun testGet() {
        println("first")
        val retrofit = Retrofit.Builder()
                .baseUrl("http://mock-api.com/2vKVbXK8.mock/")
                .addConverterFactory(GsonConverterFactory.create())  
                .build()
        val getApi = retrofit.create(GetApi::class.java)
        getApi.getUserInfo("1234")!!.enqueue(object : Callback<UserInfo?> {
            override fun onResponse(call: Call<UserInfo?>?, response: Response<UserInfo?>?) {
                if (response?.body() != null) {
                  
                    val str = response.body()!!
                    println("$str")
                }
            }

            override fun onFailure(call: Call<UserInfo?>?, t: Throwable) {
                Log.i("FragmentActivity.TAG", "onFailure: $t")
            }
        })


    }

喜歡可以加Q羣號:874826112,一起學習,成長,交流工作經驗,
記得要點贊,評論哦😯;

更多相關內容請點擊主頁查看…

簡書: https://www.jianshu.com/u/88db5f15770d

csdn:https://me.csdn.net/beyondforme

掘金:https://juejin.im/user/5e09a9e86fb9a016271294a7

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章