Reputation: 3349
I understand that this is how the interceptor works and a request from the application passes through the OkHttp core, via retrofit wrapper and OkHttpp core call to make an actual network request and the network response to the application interceptor response via the retrofit wrapper.
Is there a way to avoid calling the actual request from the application interceptor, as in, in some scenario in application interceptor check if the request URL is some string, then, in that case, do-not-call the actual network request and directly return the hard-coded response from the application interceptor?
Upvotes: 4
Views: 1624
Reputation: 3186
You can return a new Response instead of calling chain.proceed()
and it would stop the chain from moving forward. You can do it like this.
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()
I also recommend to define an annotation, and get it in your interceptor instead of checking for the URL.
request.tag(Invocation::class.java)?.method()?.getAnnotation(YourAnnotation::class.java)
Upvotes: 7
Reputation: 3192
Retrofit has so called "retrofit-mock", which is designed specifically for your task - mocking: https://github.com/square/retrofit/tree/master/retrofit-mock
You can try it, maybe you will find it useful.
Example of usage: https://github.com/square/retrofit/blob/master/samples/src/main/java/com/example/retrofit/SimpleMockService.java
You can create 2 implementations of your retrofit service - real and mocked. And provide one of them via DI depending on build flavor or application mode (demo mode or real http session).
Upvotes: -1