OKHttp Authenticator custom http code other than 401 and 407

大憨熊 提交于 2019-12-04 19:08:17

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!