OkHttpClient 成功从 API 检索数据,但在 Kotlin Android 应用程序中调用 onFailure 入队

OkHttpClient successfully retrieves data from API, but on enqueue onFailure is called in Kotlin Android application

我正尝试在 Android Studio 中使用 Kotlin 中的 retrofit2 从服务器检索数据,我收到此消息: I/okhttp.OkHttpClient: --> 获取 https://www.themealdb.com/api/json/v1/1/filter.php?&i=chicken_breast --> 结束获取 I/okhttp.OkHttpClient: <-- 200 https://www.themealdb.com/api/json/v1/1/filter.php?&i=chicken_breast (1251ms)

它也检索我想要的数据,但它调用了 onFailure 函数: I/okhttp.OkHttpClient: {"meals":[{"strMeal":"Chick-Fil-A Sandwich","strMealThumb":"https://www.themealdb.com/images/media/meals/sbx7n71587673021.jpg ","idMeal":"53016"}]} I/okhttp.OkHttpClient: <-- END HTTP (1313-byte body) I/System.输出:失败

class MainActivity : AppCompatActivity(), View.OnClickListener  {

    val menuAPI = MenuAPI.create()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val searchButton:Button = findViewById(R.id.searchButton)
        searchButton.setOnClickListener(this)
    }


    override fun onClick(v: View?) {
        menuAPI.getResults("chicken_breast").enqueue(object: retrofit2.Callback<ArrayList<Meals>>{

            override fun onFailure(call: Call<ArrayList<Meals>>, t: Throwable) {
                println()
                println("Fail")
            }

            override fun onResponse(call: Call<ArrayList<Meals>>, response: Response<ArrayList<Meals>>) {
                println("yes")
            }
        })

    }
}
interface MenuAPI {
    @GET("filter.php?")
    fun getResults(@Query("i") ingredient:String ): Call<ArrayList<Meals>>

    companion object {
        private val httpInterceptor = HttpLoggingInterceptor().apply {
            // there are different logging levels that provide a various amount of detail
            // we will use the most detailed one
            this.level = HttpLoggingInterceptor.Level.BODY
        }
        private val httpClient = OkHttpClient.Builder().apply {
            // add the interceptor to the newly created HTTP client
            this.addInterceptor ( httpInterceptor )
        }.build()

        fun create(): MenuAPI {
            val retrofit = Retrofit.Builder()
                .baseUrl ( "https://www.themealdb.com/api/json/v1/1/" )
                .addConverterFactory ( GsonConverterFactory.create() )
                .client ( httpClient )
                .build()
            return retrofit.create(MenuAPI::class.java)
        }
    }

}

从您发布的 JSON 来看,您的 getResults 函数的 return 类型似乎是错误的。 API 不是 returning 一个 List<Meals>,而是一个带有单个 属性 的对象,称为 meals,它是一个膳食列表。

我不确定你的 Meals class 是什么样子,但你需要一个包装器对象来正确表示响应。类似于:

data class Response(val meals: List<Meals>)

函数将是:

fun getResults(@Query("i") ingredient: String): Call<Response>

我假设您的 Meals class 代表列表中的单个对象。