【问题标题】:Retrofit 2 request always failure - Kotlin改造 2 请求总是失败 - Kotlin
【发布时间】:2019-05-20 16:11:36
【问题描述】:

我尝试同时学习 kotlin 和 retrofit 2。我有这个代码。

我想从this 获取所有/posts。但它总是返回一个失败代码。我是这方面的新手,谢谢

网络接口

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
}

MainActivity

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")
        }

    })
}
}

【问题讨论】:

  • onResponse你已经登录onFailure,你确定你没有对此感到困惑吗?
  • 哦,天哪,对不起我的愚蠢错误..

标签: android api kotlin retrofit retrofit2


【解决方案1】:

在 APIService 接口 @GET("posts") 中插入 @GET("/posts")

【讨论】:

    【解决方案2】:

    它总是失败,因为原因是无效的 URL。你犯的错误是'/'。您可以将斜杠('/')放在基本 URL 中或端点的开头。在您的情况下,URL 类似于 "https://jsonplaceholder.typicode.com//posts"。这是无效的,这就是您的请求失败的原因。因此,只需从 Endpoint 中删除“/”即可。

    制作请求界面如下:

    interface APIService {
    
       @GET("posts")
       fun getPosts(): Call<List<UserData>>
    
       }
    

    【讨论】:

    • 我解决了这个问题,但尝试记录数据失败。先生如何记录所有标题?
    • 就像这样 val data = response?.body() Log.d("RetrofitTest", "responsennya ${data?.size}")
    • 你调试响应了吗?
    猜你喜欢
    • 2019-02-19
    • 1970-01-01
    • 2018-01-08
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多