package com.sybotan.android.demo.retrofit;

import android.util.Log;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

import static java.nio.charset.StandardCharsets.UTF_8;


/**
 * Created by weimo on 2020/7/13.
 */
public class RetrofitLogInterceptor implements Interceptor {
    public static String TAG = "RetrofitLogInterceptor";

    @Override
    public synchronized Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        request = request.newBuilder()
                .build();
        long startTime = System.currentTimeMillis();
        Response response = chain.proceed(request);
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        MediaType mediaType = null;
        String content = "";
        if (request.body() != null) {
            mediaType = response.body().contentType();
            content = response.body().string();
            Log.e(TAG, "请求地址：| " + request.toString());
            printParams(request.body());
        }
        Log.e(TAG, "请求体返回：| Response:" + content);
        Log.e(TAG, "----------请求耗时:" + duration + "毫秒----------");
        return response.newBuilder().body(okhttp3.ResponseBody.create(mediaType, content)).build();
    }

    private void printParams(RequestBody body) {
        Buffer buffer = new Buffer();
        try {
            body.writeTo(buffer);
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = body.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF_8);
            }
            String params = buffer.readString(charset);
            Log.e(TAG, "请求参数： | " + params);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
