美文网首页
笔计:okhttp3 Interceptor 拦截器 请求前

笔计:okhttp3 Interceptor 拦截器 请求前

作者: object_cheng | 来源:发表于2017-04-28 08:58 被阅读110次


public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        //请求定制:添加请求头
        Request.Builder requestBuilder = original.newBuilder();
        String access_token = (String)SPHelper.get(BaseApplication.getAppComponent().getContext(),"access_token","");
        if(!TextUtils.isEmpty(access_token)){
            requestBuilder.addHeader("Authentication", access_token);
        }
        //请求体定制:统一添加token参数
        if (original.body() instanceof FormBody) {
            FormBody.Builder newFormBody = new FormBody.Builder();
            FormBody oidFormBody = (FormBody) original.body();
            for (int i = 0; i < oidFormBody.size(); i++) {
                newFormBody.addEncoded(oidFormBody.encodedName(i), oidFormBody.encodedValue(i));
            }
//                newFormBody.add("Authentication", "222222222222");
            requestBuilder.method(original.method(), newFormBody.build());
        }

        Request request = requestBuilder.build();
        return chain.proceed(request);
    }
}


相关文章

网友评论

      本文标题:笔计:okhttp3 Interceptor 拦截器 请求前

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