Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

source - https://square.github.io/okhttp/interceptors/

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?

like image 608
Ritt Avatar asked Nov 01 '25 12:11

Ritt


1 Answers

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)
like image 161
Amin Avatar answered Nov 03 '25 01:11

Amin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!