首页 > 解决方案 > 无法从 api 获得响应

问题描述

我有 API 新闻 它由元素 web 名称、密钥、国家/地区组成 一切都很好,我首先测试了链接: https ://newsapi.org/v2/top-headlines?country=eg&apiKey= e80f949de1a34b94804188af28f08f44 然后我构建了所需的类,并设置一个接口并放入 Headers , Query ,当我调用它时,我发现了一个错误。

/// 
public class RetrofitClient {

    private static Retrofit retrofit;

    private static final String BASE_URL = "https://newsapi.org/";

    public static Retrofit getRetrofitInstance(){
        if (retrofit == null) {
            retrofit = new retrofit2.Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
           }
       return retrofit;
    }
}


///-----


public interface GetData {

      String API_KEY="e80f949de1a34b94804188af28f08f44";

       @Headers("X-Api-Key:"+API_KEY)
       @GET("/v2/top-headlines")
       Call<List<Response>>getAllHeadlines(@Query("country") String country);

}
//- MainActivity 

   GetData service = RetrofitClient.getRetrofitInstance().create(GetData.class);
      Call<List<Response>> call = service.getAllHeadlines("eg");

        call.enqueue(new Callback<List<Response>>(){
            @Override
            public void onResponse(Call<List<Response>> call, retrofit2.Response<List<Response>> response) {
                Log.d("print","Don"+response.body());
            }

            @Override
            public void onFailure(Call<List<Response>> call, Throwable t) {
               Log.d("print","nON"+t.getMessage());
            }
        });


// Log.d 

 D/print: nONExpected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

标签: javaandroid

解决方案


这与 Gson 转换器有关。您期待一个 List 但 json 在开始时返回一个 json 对象而不是一个 json 数组。检查您的模型,以便您可以根据 json 更改它。


推荐阅读