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;
} 
发布了63 篇原创文章 · 获赞 10 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/yin13753884368/article/details/77408651