/*
 * 文 件 名:  HttpUtils
 * 版    权:
 * 描    述:  <描述>
 * 修 改 人:  learshaw
 * 修改时间:  2021/9/17
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.huashe.common.utils;

import com.huashe.common.exception.Assert;
import com.huashe.common.exception.BusinessException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HttpUtils
 * <功能详细描述>
 *
 * @author learshaw
 * @version [版本号, 2021/9/17]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class HttpUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    private static final int CONNECT_TIMEOUT = 10000;

    private static final int REQUEST_TIMEOUT = 15000;

    private static final int SOCKET_TIMEOUT = 5000;

    /**
     * 发送Get请求
     *
     * @param url 地址
     * @return 响应
     */
    public static String doGet(String url) {
        String result = null;

        try {
            // 创建HttpGet对象，并执行请求
            Assert.notEmpty(url, -1, "url 地址不合法!");
            URIBuilder uriBuilder = new URIBuilder(url);
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
            result = execute(httpGet);
        }
        catch (Exception e) {
            log.error("doGet fail!", e);
            throw new BusinessException(-1, e.getMessage(), e);
        }


        return result;
    }

    /**
     * 发送Get请求
     *
     * @param uriBuilder 地址
     * @return 响应
     */
    public static String doGet(URIBuilder uriBuilder) {
        String result = null;

        try {
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
            result = execute(httpGet);
        }
        catch (Exception e) {
            log.error("doGet fail!", e);
            throw new BusinessException(-1, e.getMessage(), e);
        }

        return result;
    }

    /**
     * 发送post请求
     *
     * @param url     地址
     * @param payload 请求参数
     * @return
     */
    public String doPost(String url, String payload) {
        String result = null;

        try {
            Assert.notEmpty(url, -1, "url 地址不合法!");
            URIBuilder uriBuilder = new URIBuilder(url);
            HttpPost httpPost = new HttpPost(uriBuilder.build());
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setEntity(new StringEntity(payload));
            result =  execute(httpPost);
        }
        catch (Exception e) {
            log.error("doPost fail!", e);
            throw new BusinessException(-1, e.getMessage(), e);
        }

        return result;
    }

    /**
     * 发送post请求
     *
     * @param uriBuilder 地址
     * @param payload 请求参数
     * @return
     */
    public String doPost(URIBuilder uriBuilder, String payload) {
        String result = null;

        try {
            HttpPost httpPost = new HttpPost(uriBuilder.build());
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setEntity(new StringEntity(payload));
            result =  execute(httpPost);
        }
        catch (Exception e) {
            log.error("doPost fail!", e);
            throw new BusinessException(-1, e.getMessage(), e);
        }

        return result;
    }

    /**
     * 发送Get请求
     *
     * @param request 请求对象
     * @return 响应
     */
    public static String execute(HttpUriRequest request) {
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;
        String result = null;

        try {
            // 创建RequestConfig对象，并设置超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT) // 设置等待数据超时时间（单位毫秒）
                .setConnectTimeout(CONNECT_TIMEOUT) // 设置连接超时时间（单位毫秒）
                .setConnectionRequestTimeout(REQUEST_TIMEOUT)// 设置从连接池获取连接的超时时间（单位毫秒）
                .build();

            // 创建HttpClient对象，并设置请求配置
            httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
            response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        }
        catch (Exception e) {
            log.error("execute fail!", e);
            throw new BusinessException(-1, e.getMessage(), e);
        }
        finally {
            CloseUtils.close(response);
            CloseUtils.close(httpClient);
        }

        return result;
    }
}