【问题标题】:cannot get response from api无法从 api 获得响应
【发布时间】:2020-08-25 18:26:01
【问题描述】:

我有 API 新闻 它由元素组成 网站名称、密钥、国家 一切都很好,我首先测试了链接: 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 $

【问题讨论】:

  • 我希望这是一个免费的 api 密钥,而不是你实际收费的,在后一种情况下你真的不应该分享它。

标签: java android


【解决方案1】:

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

【讨论】:

  • 所以你说Call&lt;List&lt;Response&gt;&gt; 中的List&lt;Response&gt; 是问题,因为API 没有返回顶级列表?
  • @luk2302 是的,就是这样。检查您的模型以查看根据 json 更改它是否有意义,或者,如果 json 是格式错误的模型,请查看实现您自己的 Gson 类型转换器,以便拦截转换,循环遍历每个对象中的键值对,假设该值可映射到您的模型,将其转换为模型,然后您就可以返回您的列表。
  • 我怀疑这是错误的模型,而不是 API / Json,因为后者是由无法更改的外部服务定义的。如果您可以将我的详细信息和您的评论包含在您的答案中,这将进一步改善答案。
  • 当我做出改变时。调用> 到
  • 但是我们为什么不使用 Call>
猜你喜欢
  • 2022-11-23
  • 2020-05-08
  • 2017-11-28
  • 2023-01-04
  • 2021-09-04
  • 2016-10-05
  • 2016-03-18
  • 1970-01-01
相关资源
最近更新 更多