OkHttp自定义拦截器打印post请求报文

OkHttp自定义拦截器打印post请求报文

背景:
我们直接使用打印request.toString或request.body时打印的携带请求头、content-type的全部请求信息,实际开发中我们可能只需要打印真实上送报文。
有以上需求的可以通过自定义日志拦截器方法处理:

第一步:自定义日志拦截器 LoggingInterceptor.java

public class LoggingInterceptor implements Interceptor {

    Context context;

    public LoggingInterceptor(Context mcontext) {

        this.context = mcontext;
    }

    public LoggingInterceptor() {
    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        //处理请求报文打印
        LogUtils.d("request.toString()== " + request.toString());
        String method = request.method();
        

	//重点部分----------针对post请求做处理-----------------------
		if ("POST".equals(method)) {//post请求需要拼接
            StringBuilder sb = new StringBuilder();
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); i++) {
                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                }
                sb.delete(sb.length() - 1, sb.length());
                LogUtils.i("请求报文: RequestParams:{" + sb.toString() + "}");
            }
        } else {//get请求直接打印url
            LogUtils.i("request params==" + request.url() + "\n 参数==" + request.body().toString());
        }


        long startTime = System.currentTimeMillis();
        Response response = chain.proceed(request);
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        LogUtils.d("----------END---------" + duration + "毫秒----");

        //处理响应报文打印
        MediaType contentType = null;
        String bodyString = null;
        if (response.body() != null) {
            contentType = response.body().contentType();
            bodyString = JsonTransfer(response.body().string());
        }
        LogUtils.d("response: " + response.code() + "\n" + bodyString);
        if (response.body() != null) {// 深坑!打印body后原ResponseBody会被清空,需要重新设置body
            ResponseBody body = ResponseBody.create(contentType, bodyString);
            return response.newBuilder().body(body).build();
        } else {
            return response;
        }
    }
}

第二步:在初始化okHttpClientBuilder 时添加拦截器


    public static OkHttpClient getOkHttpClient(Context context) {
        mContext = context;

        OkHttpClient okHttpClient = new OkHttpClient();
        OkHttpClient.Builder okHttpClientBuilder = okHttpClient.newBuilder()
                .sslSocketFactory(getSslSocketFactory())
//                .hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                })
                .addInterceptor(new LoggingInterceptor(mContext))
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true);
        return okHttpClientBuilder.build();
    }

猜你喜欢

转载自blog.csdn.net/u011084603/article/details/103687084