美文网首页
okHttp之intercepter应用场景

okHttp之intercepter应用场景

作者: 太阳晒得我丶好干瘪 | 来源:发表于2018-01-03 17:03 被阅读44次

总结下okhttp里Intercepter的应用场景:
一.刷新token:
先介绍下token的机制,客户端通过username,password获取token和refreshToken,token的有效期为2小时,refreshToken的有效期为15天,如果服务器端判断token过期,而refreshToken未过期,就返回错误码给客户端,则客户端通过一个特定的接口传入refreshToken参数获取新的token和refreshToken,如果连续15天未使用app或者用户修改了密码,则表示refreshToken过期了,则跳到登录界面,重新登录获取token和refreshToken,refreshToken存在的意义就是不用每次都要用username和password去刷新token。
1.使用okhttp提供的Authenticator接口:
如果接口返回的错误码为401,则可以使用这种方式

public class TokenAuthenticator implements Authenticator {
    @Override
    public Request authenticate(Proxy proxy, Response response) throws IOException {
        if (responseCount(response) >= 3) {
             return null; // 返回空表示不再重试,避免未知情况下的多次请求
        }
        //取出本地的refreshToken
        String refreshToken = "123456789";
        // 通过某个同步方法获取到最新的token
        String newToken =asycGetToken(refreshToken);
        return response.request().newBuilder()
                .header("Authorization", newToken)
                .build();
    }    
}

OkHttpClient client = new OkHttpClient();
client.setAuthenticator(new TokenAuthenticator());

2.使用intercepter拦截

public class TokenInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response originalResponse = chain.proceed(request);
        //获取返回的json字符串(originalResponse.body().string()好像有问题)
        ResponseBody responseBody = originalResponse.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset( Charset.forName("UTF-8"));
        }
        String bodyString = buffer.clone().readString( Charset.forName("UTF-8"));
        if (isExpired (bodyString)){//判断是否过期
            //取出本地的refreshToken
            String refreshToken = "123456789";
            // 通过某个同步方法获取到最新的token
            String newToken = asycGetToken(refreshToken);
            Request newRequest = request.newBuilder().header("Authorization", newToken)
                    .build();
            originalResponse.body().close();
            return chain.proceed(newRequest);
        }
        return originalResponse;
    }
}

二.添加公共头信息
注意okhttp的Header不能添加null,我们需要判空,否则会报空指针

public class HeaderInterceptor implements Interceptor {
    public static final String AUTHORIZATION = "Authorization";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();

        String ihuid = ConfigCompat.getIHUID() == null ? "" : ConfigCompat.getIHUID();
        String iccid = ConfigCompat.getICCID() == null ? "" : ConfigCompat.getICCID();
        String msisdn = "";
        String env_type = ConfigCompat.getTspEnv() == null ? "" : ConfigCompat.getTspEnv();
        String model = Build.PRODUCT== null ? "" : Build.PRODUCT;

        String authorization = ConfigCompat.getAccessToken();
        Request.Builder requestBuilder = original.newBuilder()
                .addHeader("Accept", "application/json")
                .addHeader("Content-type", "application/json")
                .addHeader("X-CLIENT-ID", ihuid)
                .addHeader("X-ICCID", iccid)
                .addHeader("X-VEHICLE-IDENTIFIER", "")
                .addHeader("X-ENV-TYPE", env_type)
                .addHeader("X-DEVICE-TYPE", "ihu")
                .addHeader(AUTHORIZATION, authorization)
                .addHeader("X-IHU-ID", ihuid)
                .addHeader("X-MSISDN", msisdn)
                .addHeader("X-APP-ID","M820igii5lL4tcy")
                .addHeader("X-VEHICLE-MODEL",model);

        Request request = requestBuilder.build();

        return chain.proceed(request);
    }
}

三.添加公共请求参数:
现在有个需求需要在get请求里添加参数,post请求的json里添加参数

public class ParamsInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String method = request.method();
        if (method.equalsIgnoreCase("GET")) {
            HttpUrl model = request.url().newBuilder().addQueryParameter("model", Build.PRODUCT).build();
            request = request.newBuilder().url(model).build();
        }else if (method.equalsIgnoreCase("POST")) {
            RequestBody requestBody = request.body();
            if (requestBody instanceof FormBody) {
                //application/x-www-form-urlencoded的方式提交
            } else {
                //application/json的方式提交
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);
                String oldParamsJson = buffer.readUtf8();
                HashMap<String, Object> rootMap = new Gson().fromJson(oldParamsJson, HashMap.class);
                rootMap.put("model", Build.PRODUCT);
                String newJsonParams = new Gson().toJson(rootMap);

                request = request.newBuilder().post(RequestBody.create(MediaType.parse("application/json"), newJsonParams)).build();
            }
        }
        return chain.proceed(request);
    }
}

相关文章

网友评论

      本文标题:okHttp之intercepter应用场景

      本文链接:https://www.haomeiwen.com/subject/mqccsxtx.html