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

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