OKHttp Authenticator自定义HTTP代码(401和407除外) [英] OKHttp Authenticator custom http code other than 401 and 407

查看:778
本文介绍了OKHttp Authenticator自定义HTTP代码(401和407除外)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在服务器端实现了oauth令牌,但是当令牌无效或令牌过期时,我会收到200个http状态代码,但在响应正文中,我有 {"code":"4XX", "data":{"some":"object"} 当我尝试读取interceptor中的字符串时,我得到了okhttp dispatcher java.lang.illegalstateexception closed,因为response.body().string()必须仅被调用一次.

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.

我也从这里阅读刷新OAuth使用Retrofit而不修改所有调用的令牌,我们可以使用OkHttp Authenticator类,但是它仅适用于401/407,我还没有尝试过,因为我不会得到这个.有什么方法可以自定义Authenticator并在其中进行逻辑处理. 谢谢

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

推荐答案

如果可能,请尝试与服务器端讨论响应代码.沟通也是一项非常重要的技能.

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

如果不可能,您可以使用反射手动修改响应代码,从而启用okHttp身份验证逻辑.

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.

这篇关于OKHttp Authenticator自定义HTTP代码(401和407除外)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆