我试图同时学习 kotlin 和 retrofit 2。我有这个代码。
我想获取所有来自 this 的/posts .但它总是返回一个失败代码。我是这方面的新手,谢谢
网络接口(interface)
interface APIService {
@GET("/posts")
fun getPosts(): Call<List<UserData>>
POJO 类
open class UserData {
@SerializedName("userId")
@Expose
open var user_id: Int? = null
@SerializedName("id")
@Expose
open var id: Int? = null
@SerializedName("title")
@Expose
open var title: String? = null
@SerializedName("body")
@Expose
open var body: String? = null
}
主 Activity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://jsonplaceholder.typicode.com/")
.build()
val service = retrofit.create(APIService::class.java)
service.getPosts().enqueue(object : Callback<List<UserData>> {
override fun onFailure(call: Call<List<UserData>>?, t: Throwable?) {
Log.d("RetrofitTest", t.toString())
}
override fun onResponse(call: Call<List<UserData>>?, response: Response<List<UserData>>?) {
Log.d("RetrofitTest", "onFailure")
}
})
}
}
最佳答案
在 API 服务接口(interface)中 @GET("posts") 而不是 @GET("/posts")
关于android - Retrofit 2 请求总是失败 - Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53863586/