【问题标题】:Why is my response body null, status 200?为什么我的响应正文为空,状态为 200?
【发布时间】:2021-04-05 07:13:34
【问题描述】:

我正在尝试从此 url 获取响应正文:http://192.168.0.220:8000/records/?account_id=2"

在 android studio 中,我得到状态 200,但 body 始终为空。谁能告诉我我做错了什么?

邮递员的响应如下所示:

{
    "result": [
        {
            "id": 1,
            "account_id": 2,
            "title": "ez",
            "datetime": "2021-03-21T00:00:00",
            "description": "ez2",
            "image": null,
            "recording": null
        },
        {
            "id": 2,
            "account_id": 2,
            "title": "ez",
            "datetime": "2021-03-21T00:00:00",
            "description": "ez2",
            "image": null,
            "recording": null
        },
....

android studio 中的响应:

I/System.out: Response{protocol=http/1.1, code=200, message=OK, url=http://192.168.0.220:8000/records/?account_id=2}
    Item(id=null, account_id=null, title=null, datetime=null, image=null, recording=null)

界面:

interface Gett {
    @GET("?account_id=2")
    fun getRecord(): Call<Record.Item>
}

类:

class Record {
    data class Item(
        val id: String,
        val account_id: String,
        val title: String,
        val datetime: String,
        val image: String,
        val recording: String
    )
}

主活动:

val retrofit = Retrofit.Builder()
                    .baseUrl("http://192.168.0.220:8000/records/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()


val service = retrofit.create(Gett::class.java)
            val call = service.getRecord()

call.enqueue(object : retrofit2.Callback<Record.Item> {
                override fun onResponse(call: Call<Record.Item>, response: Response<Record.Item>) {
                    if (response.code() == 200) {
                        println(response)
                        println(response.body()!!)
                    }
                }
                override fun onFailure(call: Call<Record.Item>, t: Throwable) {
                    println("fail")
                }
            })

【问题讨论】:

  • fun getRecord(): Response&lt;Record.Item&gt;

标签: android kotlin retrofit2


【解决方案1】:

问题可能是这样的

interface Gett {
    @GET("?account_id=2")
    fun getRecord(): Call<Record.Item> <----
}

所以,改变你的模型

data class Record (
    val result: List<Item>
)

data class Item(
        val id: String,
        val account_id: String,
        val title: String,
        val datetime: String,
        val image: String,
        val recording: String
    )

正如我所见,您的 JSON 中有一个 Item 数组,因此请将其更改为。

interface Gett {
    @GET("?account_id=2")
    fun getRecord(): Call<Record>
}

感谢@Kunn 指出 JSONObject。

【讨论】:

  • 响应不是列表。这是一个 JsonObject。
猜你喜欢
  • 1970-01-01
  • 2020-09-26
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 2016-11-29
  • 2013-03-24
  • 2017-10-31
  • 1970-01-01
相关资源
最近更新 更多