首页
/ Retrofit-Spring-Boot-Starter 中实现响应内容预处理的最佳实践

Retrofit-Spring-Boot-Starter 中实现响应内容预处理的最佳实践

2025-07-07 02:57:05作者:邵娇湘

在实际开发中,我们经常会遇到需要统一处理API响应格式的场景。特别是在使用Retrofit作为HTTP客户端时,如何优雅地处理固定的响应结构是一个值得探讨的话题。

常见的响应格式问题

典型的API响应往往采用统一包装格式,例如:

{
    "code": 200,
    "data": {},
    "msg": null
}

其中:

  • code字段表示业务状态码
  • data字段包含实际业务数据
  • msg字段用于错误信息提示

这种设计虽然规范,但直接使用会导致每个接口都需要重复处理这些包装逻辑,增加了代码冗余和维护成本。

解决方案:自定义CallAdapter

Retrofit的强大之处在于其高度可扩展性,通过自定义CallAdapter可以完美解决这个问题。CallAdapter是Retrofit中负责将Call对象转换为其他类型(如RxJava Observable)的适配器。

实现步骤

  1. 创建自定义CallAdapterFactory: 继承CallAdapter.Factory类,实现自定义逻辑

  2. 响应处理逻辑

    • 检查HTTP状态码
    • 解析JSON响应
    • 验证业务状态码
    • 提取data字段或抛出异常
  3. 注册自定义Factory: 通过Retrofit.Builder添加到Retrofit实例

核心代码示例

public class UnifiedResponseAdapterFactory extends CallAdapter.Factory {
    
    @Override
    public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
        // 判断是否需要处理该返回类型
        if (getRawType(returnType) != Call.class) {
            return null;
        }
        
        // 获取实际响应类型
        Type responseType = getCallResponseType(returnType);
        
        return new CallAdapter<Object, Call<?>>() {
            @Override
            public Type responseType() {
                return responseType;
            }

            @Override
            public Call<Object> adapt(Call<Object> call) {
                return new UnifiedResponseCall<>(call);
            }
        };
    }
}

UnifiedResponseCall实现

class UnifiedResponseCall<T> implements Call<T> {
    private final Call<Response<T>> delegate;

    UnifiedResponseCall(Call<Response<T>> delegate) {
        this.delegate = delegate;
    }

    @Override
    public void enqueue(Callback<T> callback) {
        delegate.enqueue(new Callback<Response<T>>() {
            @Override
            public void onResponse(Call<Response<T>> call, retrofit2.Response<Response<T>> response) {
                if (response.isSuccessful()) {
                    Response<T> body = response.body();
                    if (body.getCode() == 200) {
                        callback.onResponse(UnifiedResponseCall.this, 
                            retrofit2.Response.success(body.getData()));
                    } else {
                        callback.onFailure(UnifiedResponseCall.this, 
                            new BusinessException(body.getCode(), body.getMsg()));
                    }
                } else {
                    callback.onFailure(UnifiedResponseCall.this, 
                        new HttpException(response.code(), response.message()));
                }
            }

            @Override
            public void onFailure(Call<Response<T>> call, Throwable t) {
                callback.onFailure(UnifiedResponseCall.this, t);
            }
        });
    }
    
    // 其他必要方法实现...
}

业务异常处理

建议定义自定义异常类来区分不同类型的错误:

public class BusinessException extends RuntimeException {
    private final int code;
    
    public BusinessException(int code, String message) {
        super(message);
        this.code = code;
    }
    
    public int getCode() {
        return code;
    }
}

在Spring Boot中集成

在Retrofit-Spring-Boot-Starter中,可以通过配置类轻松注册自定义CallAdapter:

@Configuration
public class RetrofitConfig {
    
    @Bean
    public UnifiedResponseAdapterFactory unifiedResponseAdapterFactory() {
        return new UnifiedResponseAdapterFactory();
    }
}

优势总结

  1. 代码简洁:接口方法直接返回业务数据类型,无需处理包装逻辑
  2. 统一异常处理:集中管理业务异常和HTTP异常
  3. 易于维护:修改响应格式处理逻辑只需调整一处
  4. 类型安全:保持Retrofit强类型检查的优势

通过这种方式,开发者可以专注于业务逻辑开发,而将重复的响应处理工作交给框架自动完成,大幅提升开发效率和代码质量。

登录后查看全文
热门项目推荐
相关项目推荐