package com.tuoheng.common.config.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * 默认拦截器
 */
public class DefaultClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultClientHttpRequestInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        trackRequest(request,body);
        ClientHttpResponse httpResponse = execution.execute(request, body);
        trackResponse(httpResponse);
        return httpResponse;
    }

    private void trackResponse(ClientHttpResponse httpResponse)throws IOException {
        LOGGER.info("============================response begin==========================================");
        LOGGER.info("Status code  : {}", httpResponse.getStatusCode());
        LOGGER.info("Status text  : {}", httpResponse.getStatusText());
        LOGGER.info("Headers      : {}", httpResponse.getHeaders());
        LOGGER.info("=======================response end=================================================");
    }

    private void trackRequest(HttpRequest request, byte[] body)throws UnsupportedEncodingException {
        LOGGER.info("======= request begin ========");
        LOGGER.info("uri : {}", request.getURI());
        LOGGER.info("method : {}", request.getMethod());
        LOGGER.info("headers : {}", request.getHeaders());
        LOGGER.info("request body : {}", new String(body, "UTF-8"));
        LOGGER.info("======= request end ========");
    }
}
