改造 - 是否可以避免从应用程序拦截器和 return 硬编码响应中调用实际的 api?

Retrofit - Is it possible to avoid calling actual api from application interceptor and return hard-coded response?

我明白拦截器是这样工作的,来自应用程序的请求通过 OkHttp 核心,通过改装包装器和 OkHttpp 核心调用进行实际的网络请求,网络响应通过改造包装纸。

有没有办法避免从应用程序拦截器调用实际请求,例如,在某些情况下,应用程序拦截器检查请求 URL 是否是某个字符串,然后,在那种情况下,做 -不调用实际的网络请求并直接 return 来自应用程序拦截器的硬编码响应?

Retrofit 有所谓的“retrofit-mock”,它是专门为您的任务设计的——模拟: https://github.com/square/retrofit/tree/master/retrofit-mock

你可以试试看,也许你会觉得有用。

使用示例: https://github.com/square/retrofit/blob/master/samples/src/main/java/com/example/retrofit/SimpleMockService.java

您可以创建改造服务的 2 个实现 - 真实的和模拟的。并根据构建风格或应用程序模式(演示模式或真实 http 会话)通过 DI 提供其中之一。

您可以 return 一个新的响应而不是调用 chain.proceed(),这会阻止链向前移动。你可以这样做。

if(something)
    return Response.Builder()
           .code(200) //Or whatever you might later check from
           .protocol(Protocol.HTTP_2) //or 1
           .message("SUCCESS")
           .body(ResponseBody.create(MediaType.get("application/json"), "{\"x\": 1}")) // your response
           .request(chain.request())
           .build()

我还建议定义一个注解,并在拦截器中获取它,而不是检查 URL。

 request.tag(Invocation::class.java)?.method()?.getAnnotation(YourAnnotation::class.java)