kotlin: 用Retrofit访问网络接口
一,安装第三方库
build.gradle.kts中添加
implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
implementation("com.google.code.gson:gson:2.13.0")
然后点击:Sync Now 链接
二,代码:
json.php

model类
package com.example.okdemo2.fragment
//import com.google.gson.annotations.
import com.google.gson.annotations.SerializedName
import java.io.Serializable
open class ApiResponse<T>(
open val data: T? = null,
open val code: Int = -1,
open val msg: String = "",
open val status: String? = null,
open val time: String? = null,
open val error: Throwable? = null,
) : Serializable {
val isSuccess: Boolean
get() = code == 200
}
data class UserList(
@SerializedName("list")
val `list`: MutableList<UserListItem>,
@SerializedName("curpage")
val curPage: Int,
@SerializedName("total")
val total: Int,
@SerializedName("totalpage")
val totalPage: Int
) : Serializable
data class UserListItem(
@SerializedName("id")
val id: Int,
@SerializedName("name")
val name: String,
@SerializedName("image")
val image: String,
) : Serializable
接口列表:
package com.example.okdemo2.fragment
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
interface ApiService {
@GET("/json.php")
fun queryUser() : Call<ApiResponse<UserList>>
}
调用retrofit访问接口
//按钮点击
binding.getJsonButton.setOnClickListener {
println("按钮被点击了")
val retrofit = Retrofit.Builder()
.baseUrl("http://www.testit.net")
.addConverterFactory(GsonConverterFactory.create())
.build()
val appService = retrofit.create(ApiService::class.java)
appService.queryUser().enqueue(object: Callback<ApiResponse<UserList>> {
override fun onResponse(call: Call<ApiResponse<UserList>>, response: Response<ApiResponse<UserList>>) {
if (response.isSuccessful) {
val user = response.body()
if (user?.status == "success") {
println("成功")
println(user?.data?.list)
} else {
println("失败")
}
}
}
override fun onFailure(call: Call<ApiResponse<UserList>>, t: Throwable) {
println("Retrofit onFailure:${t.message}")
}
})
}
三,运行结果 :

浙公网安备 33010602011771号