package com.dxhy.common.util;

import java.net.URLDecoder;

import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiaohongyang
 */
@Slf4j
public class HttpRequestUtils {

    /**
     * 
     * https请求对象
     * 
     * CloseableHttpClient
     * 
     * @author X Yang
     * @date 2017年6月28日 下午1:27:47
     */
    private static CloseableHttpClient getHttpClient() {
        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
        ConnectionSocketFactory plainsf = new PlainConnectionSocketFactory();
        registryBuilder.register("http", plainsf);
        Registry<ConnectionSocketFactory> registry = registryBuilder.build();
        // 设置连接管理器
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
        // 构建客户端
        return HttpClientBuilder.create().setConnectionManager(connManager).build();
    }

    /**
     * 
     * https post请求，参数为字符串
     * 
     * @param param
     *            参数
     * @param url
     *            地址
     * @throws Exception
     *             异常信息
     */
    public static String httpPost(String param, String url) throws Exception {
        CloseableHttpClient httpclient = getHttpClient();
        RequestConfig defaultRequestConfig =
            RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000).build();

        String result = null;
        try {
            HttpPost request = new HttpPost(url);
            // 解决中文乱码问题
            StringEntity entity = new StringEntity(param, "utf-8");
            entity.setContentType("application/json");
            request.setEntity(entity);
            // 设置请求和传输超时时间
            request.setConfig(defaultRequestConfig);
            CloseableHttpResponse response = getHttpClient().execute(request);
            url = URLDecoder.decode(url, "UTF-8");
            log.info("请求接口：" + url + ",执行状态：" + response.getStatusLine().getStatusCode());
            // 请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                try {
                    // 读取服务器返回过来的字符串数据
                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
                } catch (Exception e) {
                    log.error("post请求提交失败:" + url, e);
                } finally {
                    response.close();
                }
            } else {
                result = response.getStatusLine().getStatusCode() + "-" + response.getStatusLine().getReasonPhrase();
            }
        } catch (Exception e) {
            log.error("post请求提交失败:" + url, e);
        } finally {
            httpclient.close();
        }
        return result;
    }

}
