LogInterceptor

1,014 阅读1分钟

package com.gyc.mytestapplication.rxtest.net;

import java.io.IOException;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import timber.log.Timber;

/**
 * Created by hch on 2018/9/26.
 *
 * response.body() can only be called once , build new one after log
 */
public class LogInterceptor implements Interceptor {

    public static final String TAG = "LogInterceptor";

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

        Request request = chain.request();
        print(request);
        Response response;
        try {
            response = chain.proceed(request);
            return print(response);
        }catch (Exception e){
            e.printStackTrace();
            throw  e;
        }
        // to fix java.lang.IllegalStateException: closed . response.body().string() can only be called once
//        return null;
    }

    private void print(Request request) {
        try {
            String url = request.url().toString();
            Headers headers = request.headers();

            Timber.tag(TAG).d("url : " + url);
            Timber.tag(TAG).d("method : " + request.method());
            if (headers != null && headers.size() > 0) {
                Timber.tag(TAG).d("headers : " + headers.toString());
            }
            RequestBody requestBody = request.body();
            if (requestBody != null) {
                MediaType mediaType = requestBody.contentType();
                if (mediaType != null) {
                    if (isText(mediaType)) {
                        Timber.tag(TAG).d("request ---> %s" , bodyToString(request));
                    } else {
                        Timber.tag(TAG).d("params : " + " maybe [file part] , too large to print , ignored!");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Response print(Response response) {
        try {
            ResponseBody body = response.body();
            if (body != null) {
                MediaType mediaType = body.contentType();
                if (mediaType != null) {
                    if (isText(mediaType)) {
                        String resp = body.string();
                        Timber.tag(TAG).d("response ---> %s" , resp);

                        body = ResponseBody.create(mediaType, resp);
                        return response.newBuilder().body(body).build();
                    } else {
                        Timber.tag(TAG).d("data : " + " maybe [file part] , too large too print , ignored!");
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.newBuilder().build();
    }


    private boolean isText(MediaType mediaType) {
        if (mediaType == null) return false;

        return ("text".equals(mediaType.subtype())
                || "json".equals(mediaType.subtype())
                || "xml".equals(mediaType.subtype())
                || "html".equals(mediaType.subtype())
                || "webviewhtml".equals(mediaType.subtype())
                || "x-www-form-urlencoded".equals(mediaType.subtype()));
    }

    private String bodyToString(final Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "something error when show requestBody.";
        }
    }
}