【问题标题】:Retrofit - Is it possible to avoid calling actual api from application interceptor and return hard-coded response?改造 - 是否可以避免从应用程序拦截器调用实际 api 并返回硬编码响应?
【发布时间】:2023-03-23 20:17:01
【问题描述】:

我知道拦截器是这样工作的,来自应用程序的请求通过 OkHttp 核心,通过改造包装器和 OkHttpp 核心调用发出实际的网络请求,网络响应通过改造包装器对应用程序拦截器响应作出响应.

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

【问题讨论】:

    标签: android retrofit okhttp interceptor


    【解决方案1】:

    您可以返回一个新的响应而不是调用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)
    

    【讨论】:

      【解决方案2】:

      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 提供其中之一。

      【讨论】:

        猜你喜欢
        • 2016-05-02
        • 2013-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        • 2015-12-16
        • 1970-01-01
        相关资源
        最近更新 更多