Do we have any possibility to stop request in OkHttp Interceptor?
One thing missing in the accepted answer is that you need to specify the protocol and the message. If you don't specify that you will get an Exception. Looking like this:
if (App.specialFlag) {
return new Response.Builder()
.code(418) // Whatever code
.body(ResponseBody.create(null, "")) // Whatever body
.protocol(Protocol.HTTP_2)
.message("Dummy response")
.request(chain.request())
.build();
} else {
return chain.proceed(chain.request());
}
One way to prevent request from being executed(before it starts) it to simply do as you tried to, but with an addition of Response.Builder:
if (App.specialFlag) {
return new Response.Builder()
.code(600) //Simply put whatever value you want to designate to aborted request.
.protocol(Protocol.HTTP_2)
.message("Dummy response")
.request(chain.request())
.build();
} else {
return chain.proceed(chain.request());
}
EDIT 26/09/2019 Updated answer with details mentioned by Bobstring