[英]why is my retrofit call is returning an unsuccessful response?
所以基本上我正在使用 retrofit 從名為 calorieNinja 的 api 獲取數據,由於某種原因,我一直收到不成功的響應
這是 retrofit 代碼:
retrofit = new Retrofit.Builder().baseUrl("https://api.calorieninjas.com/v1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiCalorieNinjas apiCalorieNinjas = retrofit.create(ApiCalorieNinjas.class);
Call<MealCalories> call = apiCalorieNinjas.getMeal("nutrition?query= 5 eggs");
call.enqueue(new Callback<MealCalories>() {
@Override
public void onResponse(Call<MealCalories> call, Response<MealCalories> response) {
if(!response.isSuccessful()){
Toast.makeText(getContext(),"Not Found",Toast.LENGTH_SHORT).show();
return;
}
mealEaten = response.body();
Meal meal1 = new Meal(mealEaten.getName(),mealEaten.getCalories(),mealEaten.getProtein_g(),mealEaten.getCarbohydrates_total_g());
mealViewModel.insertMeal(meal1);
}
@Override
public void onFailure(Call<MealCalories> call, Throwable t) {
}
});
}
});
順便說一句,我正在使用 2 種不同類型的用餐對象,因為一種負責從 api 獲取數據,另一種用作 Room 數據庫的實體,它們沒有相同的參數,所以我決定使用兩種不同的而不是僅僅添加 @Ignore對象,而我嘗試解決此問題。
這是它的界面:
public interface ApiCalorieNinjas {
@Headers("X-Api-Key: PiQfBb0CZy2GfOZWjWyj6Tg==EdGjoESjqxQh1q4M")
@GET("{meal}")
public Call<MealCalories> getMeal(@Path("meal") String meal);
api 密鑰不是真的!
如果需要其他代碼,請告訴我!
嘗試添加一個攔截器,以便您可以查看所有調用日志(標頭、正文、URL 等)並查看 API 發送的錯誤是什么。
將OkHtpp
添加到您的成績依賴項:
implementation "com.squareup.okhttp3:okhttp:5.0.0-alpha.2"
implementation "com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2"
之后,當您創建 Retrofit 實例時,添加攔截器,應該如下所示:
val httpClient = OkHttpClient.Builder()
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
httpClient.addInterceptor(interceptor)
httpClient.addInterceptor(Interceptor { chain: Interceptor.Chain ->
val original: Request = chain.request()
val request: Request = original.newBuilder()
.header("Content-Type", "application/json")
.method(original.method, original.body)
.build()
chain.proceed(request)
})
val okHttpClient = httpClient.build()
val retrofit = Retrofit.Builder()
.baseUrl("https://api.calorieninjas.com/v1/")
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.