OkHttp + Retrofit 拦截器 拼装参数拦截器 日志输出拦截器

OkHttp + Retrofit 拦截器 拼装参数拦截器 日志输出拦截器

 //手动创建一个OkHttpClient并设置超时时间缓存等设置
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new LoggingInterceptor(user_token, user_only_account));//拼装公共参数
//        builder.addInterceptor(new LogInterceptor());//日志拦截器
        builder.connectTimeout(connectTime, TimeUnit.MINUTES);
        builder.readTimeout(60, TimeUnit.MINUTES);
        builder.writeTimeout(60, TimeUnit.MINUTES);
        if (RxRetrofitApp.isDebug()) {
            builder.addInterceptor(getHttpLoggingInterceptor());
        }

   /*创建retrofit对象*/
        final Retrofit retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(baseUrl)
                .build();
        return retrofit;

拼装公共参数拦截器

public class LoggingInterceptor implements Interceptor {
    private String user_token;
    private String user_only_account;

    public LoggingInterceptor(String user_token, String user_only_account) {
        this.user_token = user_token;
        this.user_only_account = user_only_account;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder newBuilder = request.newBuilder();//用来追加参数
        FormBody formBody = new FormBody.Builder()
                .add("user_token", user_token)
                .add("user_only_account", user_only_account)
                .build();
        String bodyToString = bodyToString(request.body());
        bodyToString += ((bodyToString.length() > 0) ? "&" : "") + bodyToString(formBody);
        Request build = newBuilder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), bodyToString))
                .build();
        return chain.proceed(build);
    }

    /**
     * 将公共参数拼装
     * @param request
     * @return
     */
    private String bodyToString(RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }
}

日志输出拦截器

/**
 * 日志输出
 * 自行判定是否添加
 *
 * @return
 */
private HttpLoggingInterceptor getHttpLoggingInterceptor() {
    //日志显示级别
    HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
    //新建log拦截器
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            if (TextUtils.isEmpty(message)) return;
            String s = message.substring(0, 1);
            if ("{".equals(s) || "[".equals(s)) {
                LogUtil.e("RxRetrofit", "Retrofit====Message:" + message);
            }

            try {
                JSONObject jsonObject = new JSONObject(message);
                if (jsonObject.has("resCode")) {
                    String resCode = jsonObject.optString("resCode");
                    if (resCode.equals("-1")) {
                        System.exit(0);
                        LogUtil.e("manager-->>" + resCode);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
    loggingInterceptor.setLevel(level);
    return loggingInterceptor;
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值