4

I have oauth token implemented on server side but upon Invalid token or Token expirey i am getting 200 http status code but in response body i have {"code":"4XX", "data":{"some":"object"} When i try to read string in interceptor i get okhttp dispatcher java.lang.illegalstateexception closed because response.body().string() must be called only once.

Also i read from here Refreshing OAuth token using Retrofit without modifying all calls that we can use OkHttp Authenticator class but it works only with 401/407 i havent triedn as i will not get this. Is there any way we can customize Authenticator and proceed our logic inside it. Thank you

Community
  • 1
  • 1
silentsudo
  • 6,730
  • 6
  • 39
  • 81

1 Answers1

2

If it possible, try to talk with your server side about response codes. Communication is also a very important skill.

If it inpossible, you can modify response codes manually with reflection, it enables okHttp authentication logic.

public OkHttpClient getOkHttpClient() {
    return new OkHttpClient.Builder()
            .authenticator((route, response) -> {
                System.out.println("it working");
                return null;
            })
            .addNetworkInterceptor(new UnauthorizedCaseParserInterceptor())
            .build();
}


public class UnauthorizedCaseParserInterceptor implements Interceptor {

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (isUnauthorizedResponse(response)) {
            try {
                Field codeField = response.getClass().getDeclaredField("code");
                codeField.setAccessible(true);
                codeField.set(response, HttpURLConnection.HTTP_UNAUTHORIZED);
            } catch (Exception e) {
                return response;
            }
        }
        return response;
    }

    private boolean isUnauthorizedResponse(Response response) {
        //parse response...
    }
}

Please use this solution only as a last resort.

Anrimian
  • 4,257
  • 4
  • 22
  • 30
  • I Agree, but since other systems are build using old response code only, so for them it is not possible to change, i already did this using parse response... but it again 2 ways parsing instead. Which is waste. Thanks for response anyways. – silentsudo Dec 28 '17 at 09:14