package com.stm.asset.http;

import android.util.Log;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 类名称：LoggingInterceptor
 * 类描述：请求日志拦截
 * 创建人：story
 * 创建时间：2021-12-10 17:35
 */
public class LoggingInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        Log.i("LoggingInterceptor", String.format("请求地址: %s", response.request().url()));
        ResponseBody responseBody = response.body();
        if (responseBody != null) {
            try {
                MediaType mediaType = responseBody.contentType();
                byte[] responseBytes = responseBody.bytes();
                Log.i("LoggingInterceptor", String.format("请求返回：%s", new String(responseBytes)));
                response = response.newBuilder()
                        .body(ResponseBody.create(mediaType, responseBytes))
                        .build();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        if (responseBody != null && responseBody.contentLength() > 0) {
//            BufferedSource bufferedSource = responseBody.source();
//            bufferedSource.request(Long.MAX_VALUE);
//            Buffer buffer = bufferedSource.getBuffer();
//            Charset charset = Charset.forName("utf-8");
//            MediaType contentType = responseBody.contentType();
//            if (contentType != null) {
//                try {
//                    charset = contentType.charset(Charset.forName("utf-8"));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//            if (charset != null) {
//                String result = buffer.clone().readString(charset);
//                Log.i("LoggingInterceptor", String.format("请求返回：%s", result));
//            }
//        }
        return response;
    }

}
