OKHttp Authenticator custom http code other than 4

2020-07-27 05:14发布

问题:

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

回答1:

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.