android - Retrofit 2 请求总是失败 - Kotlin

标签 android api kotlin retrofit retrofit2

我试图同时学习 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/

相关文章:

android - 有没有办法在模拟器中将 ro.kernel.qemu 设置为 0?

android - 在 Android Studio 中禁用背景突出显示

api - 发布商的广告网络,有没有 API?

kotlin - 为什么 Kotlin 接口(interface)是 "not open"?

kotlin - 这是 Kotlin REPL 的错误吗?

docker - 如何设置 micronaut 生成 docker 镜像

android - 如何禁用广播接收器以停止接收来电?

Android alsa snd_pcm_open default no such file o 目录

c# - 如何在 asp.net web api 中实现幂等 key ?

python - 如何在 Python 中使用新的 Twitter API 1.1 搜索?