【问题标题】:Retrofit 2 - How to make request without Call objectRetrofit 2 - 如何在没有 Call 对象的情况下发出请求
【发布时间】:2020-04-09 23:43:52
【问题描述】:

我使用改造 2,并且我有带有返回对象调用的其余方法的 UserService。 我想调用这些方法并只返回数据对象。

我有这个:

@GET("users")
Call<List<UserDTO>> getUsers();

但我想要:

@GET("users")
List<UserDTO> getUsers();

我知道在改造 1.9 中默认情况下这是可能的,但我找不到这个问题的解决方案。 我不想每次使用时调用方法,执行调用,获取正文并尝试..catch。

当我从第二个示例调用方法时,我收到错误:

Could not locate call adapter for java.util.List<>

是否可以在任何适配器中处理这种情况?又该怎么做呢?

【问题讨论】:

    标签: java rest api retrofit2


    【解决方案1】:

    我这样解决了这个问题:

    public class CustomCallAdapter<T> implements CallAdapter<T, T> {
    
        private Type returnType;
    
        public CustomCallAdapter(Type returnType) {
            this.returnType = returnType;
        }
    
        @Override
        public Type responseType() {
            return returnType;
        }
    
        @Override
        public T adapt(Call<T> call) {
            try {
                return call.execute().body();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    
        public static class Factory extends CallAdapter.Factory {
    
            @Override
            public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
                return new CustomCallAdapter(returnType);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 2011-09-02
      • 2012-10-29
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      相关资源
      最近更新 更多