package com.cmeeting.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustStrategy;
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.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class HttpClientUtils {

    private static RequestConfig requestConfig = null;

    static {
        // 设置请求和传输超时时间
        requestConfig = RequestConfig.custom().setSocketTimeout(180000).setConnectTimeout(180000).setConnectionRequestTimeout(180000).build();
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static JSONObject httpGet(String url) {
        log.info("请求地址：【{}】", url);
        // get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);
            // 请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // 把json字符串转换成json对象
                jsonResult = JSONObject.parseObject(strResult);

                log.info("请求返回结果：【{}】", jsonResult.toJSONString());
            } else {
                log.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            log.error("get请求提交失败:" + url, e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

    public static JSONObject httpGet(String url, String token) {
        log.info("请求地址：【{}】", url);
        // get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpGet request = new HttpGet(url);
        if (token != null) {
            request.setHeader("Authorization", "Bearer " + token);
        }
        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);
            // 请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // 把json字符串转换成json对象
                jsonResult = JSONObject.parseObject(strResult);

                log.info("请求返回结果：【{}】", jsonResult.toJSONString());
            } else {
                log.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            log.error("get请求提交失败:" + url, e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

    public static JSONObject httpGet(String url, String token, List<Header> headers, boolean isSafe) {
        log.info("请求地址：【{}】", url);
        // get请求返回结果
        JSONObject jsonResult = null;
        // 发送get请求
        HttpGet request = new HttpGet(url);
        if (token != null) {
            request.setHeader("Authorization", "Bearer " + token);
        }
        // 设置头参数
        if (CollectionUtils.isNotEmpty(headers)) {
            for (Header item : headers) {
                request.setHeader(item.getName(), item.getValue());
                log.info("请求Header：{}={}", item.getName(), item.getValue());
            }
        }
        request.setConfig(requestConfig);
        try {
            CloseableHttpClient client = null;
            if(isSafe){
                client = HttpClientBuilder.create().build();
            }else{
                // 创建一个信任所有证书的SSLContext
                SSLContext sslContext = SSLContextBuilder.create()
                        .loadTrustMaterial(new TrustStrategy() {
                            @Override
                            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                                return true; // 忽略所有证书验证
                            }
                        })
                        .build();
                client = HttpClientBuilder.create().setSSLContext(sslContext)
                        .setSSLHostnameVerifier(new NoopHostnameVerifier())
                        .build();
            }
            CloseableHttpResponse response = client.execute(request);
            // 请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // 把json字符串转换成json对象
                jsonResult = JSONObject.parseObject(strResult);

                log.info("请求返回结果：【{}】", jsonResult.toJSONString());
            } else {
                log.error("get请求提交失败:{},code:{}" ,url,response.getStatusLine().getStatusCode());
            }
        } catch (IOException | NoSuchAlgorithmException | KeyStoreException e) {
            log.error("get请求提交失败:" + url, e);
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * get请求，参数放在map里
     *
     * @param url 请求地址
     * @param map 参数map
     * @return 响应
     */
    public static JSONObject getMap(String url, Map<String, String> map) {
        log.info(url + "getMap-start :" + System.currentTimeMillis());
        log.info("请求地址：【{}】", url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        List<NameValuePair> pairs = new ArrayList<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameters(pairs);
            HttpGet get = new HttpGet(builder.build());
            response = httpClient.execute(get);
            log.info(url + "getMap-end :" + System.currentTimeMillis());
            HttpEntity entity = response.getEntity();
            String resultJson = EntityUtils.toString(entity);
            log.info("请求返回的原始数据：【{}】", resultJson);
            JSONObject result = JSONObject.parseObject(resultJson);

            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                log.info("返回结果：【{}】", result.toJSONString());
            } else {
                log.info("返回结果异常：【{}】", result.toJSONString());
            }
            return result;
        } catch (URISyntaxException e) {
            log.error("请求失败", e);
        } catch (ClientProtocolException e) {
            log.error("请求失败", e);
        } catch (IOException e) {
            log.error("请求失败", e);
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    public static JSONObject postForForm(String url, Map<String, String> parms) {
        log.info("请求地址：{}", url);
        HttpPost httpPost = new HttpPost(url);
        ArrayList<BasicNameValuePair> list = new ArrayList<>();
        parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value)));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            if (Objects.nonNull(parms) && parms.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            }
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));

            log.info("请求结果：{}", jsonObject.toJSONString());

            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(httpClient)) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * get请求(用于key-value格式的参数,且带有header请求头)
     *
     * @param url
     * @param map 请求的参数map<key,value>键值对
     * @return
     */
    public static String doGet(String url, Map<String, String> map) {
        log.info("请求地址：【{}】", url);
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String entityStr = null;
        CloseableHttpResponse response = null;

        try {
            /*
             * 由于GET请求的参数都是拼装在URL地址后方，所以我们要构建一个URL，带参数
             */
            URIBuilder uriBuilder = new URIBuilder(url);
            /** 第一种添加参数的形式 */
            /*uriBuilder.addParameter("name", "root");
            uriBuilder.addParameter("password", "123456");*/

            for (Map.Entry<String, String> entry : map.entrySet()) {
                uriBuilder.addParameter(entry.getKey(), entry.getValue());
            }


            /** 第二种添加参数的形式 */
            /* List<NameValuePair> list = new LinkedList<>();
            BasicNameValuePair param1 = new BasicNameValuePair("startTime", "2019-1-1 00:00:00");
            BasicNameValuePair param2 = new BasicNameValuePair("endTime", "2019-1-9 00:00:00");
            list.add(param1);
            list.add(param2);
            uriBuilder.setParameters(list);*/

            // 根据带参数的URI对象构建GET请求对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            /*
             * 添加请求头信息
             */
            // 浏览器表示
            httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            // 传输的类型
            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
            //header的<key,value>
            //httpGet.setHeader(headerKey, headerValue);

            // 执行请求
            response = httpClient.execute(httpGet);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");

            log.info("返回结果：【{}】", entityStr);
        } catch (ClientProtocolException e) {
            log.error("Http协议出现问题", e);
        } catch (ParseException e) {
            log.error("解析错误", e);
        } catch (URISyntaxException e) {
            log.error("URI解析异常", e);
        } catch (IOException e) {
            log.error("IO异常", e);
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return entityStr;
    }


    /**
     * post请求传输json参数
     *
     * @param url url地址
     * @return
     */
    public static JSONObject httpPost(String url, cn.hutool.json.JSONObject jsonParam, String token) {

        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        if (token != null) {
            httpPost.setHeader("Authorization", "Bearer " + token);
        }
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    log.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            log.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    public static JSONObject httpPost(String url, JSONObject jsonParam, String token) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        if (token != null) {
            httpPost.setHeader("Authorization", "Bearer " + token);
        }
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    log.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            log.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * post请求传输String参数 例如：name=Jack&sex=1&type=2
     * Content-type:application/x-www-form-urlencoded
     *
     * @param url      url地址
     * @param strParam 参数
     * @return
     */
    public static JSONObject httpPost(String url, String strParam) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try {
            if (null != strParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(strParam, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    log.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            log.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * 发送POST请求
     *
     * @param url
     * @param header
     * @param parametersBody
     * @param timeout
     * @return
     */
    public static JSONObject postRequest(String url, List<Header> header, String parametersBody, Integer timeout) {
        log.info("请求地址：{}", url);
        log.info("请求方式：POST");
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-Type", "application/json;charset=UTF-8");
        post.addHeader("Accept", "application/json");
        // 设置头参数
        if (CollectionUtils.isNotEmpty(header)) {
            for (Header item : header) {
                post.setHeader(item.getName(), item.getValue());
                log.info("请求Header：{}={}", item.getName(), item.getValue());
            }
        }
        try {
            StringEntity entity = new StringEntity(parametersBody);
            post.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 请求参数

        if (timeout != null && timeout.intValue() > 0) {
            RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
            post.setConfig(config);
        }

        try {
            log.info("请求参数：{}", parametersBody);
            CloseableHttpClient client = HttpClientBuilder.create().build();
            HttpResponse response = client.execute(post);
            int code = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            String s = EntityUtils.toString(entity);
            JSONObject result = (JSONObject) JSONObject.parseObject(s);
            if (code >= 400) {
                throw new RuntimeException(result.toJSONString());
            }

            log.info("请求返回结果：{}", result);
            return result;
        } catch (ClientProtocolException e) {
            throw new RuntimeException("postRequest -- Client protocol exception!", e);
        } catch (IOException e) {
            throw new RuntimeException("postRequest -- IO error!", e);
        } finally {
            post.releaseConnection();
        }
    }

    /**
     * 发送POST请求
     *
     * @param url
     * @param headerParams
     * @param parametersBody
     * @param timeout
     * @return
     */
    public static JSONObject postJsonRequest(String url, Map<String, String> headerParams, String parametersBody, Integer timeout) {
        log.info("请求地址：{}", url);
        log.info("请求方式：POST");
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-Type", "text/plain");
        // 设置头参数
        //设置请求头
        if (headerParams != null && headerParams.size() > 0) {
            for (Map.Entry<String, String> e : headerParams.entrySet()) {
                String value = e.getValue();
                String key = e.getKey();
                if (StrUtil.isNotBlank(value)) {
                    post.setHeader(key, value);
                }
            }
        }
        try {
            StringEntity entity = new StringEntity(parametersBody);
            entity.setContentType("text/plain");
            entity.setContentEncoding("UTF-8");
            post.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 请求参数

        if (timeout != null && timeout.intValue() > 0) {
            RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
            post.setConfig(config);
        }

        try {
            log.info("请求参数：{}", parametersBody);
            CloseableHttpClient client = HttpClientBuilder.create().build();
            HttpResponse response = client.execute(post);
            int code = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            String s = EntityUtils.toString(entity);
            JSONObject result = (JSONObject) JSONObject.parseObject(s);
            if (code >= 400) {
                throw new RuntimeException(result.toJSONString());
            }

            log.info("请求返回结果：{}", result);
            return result;
        } catch (ClientProtocolException e) {
            throw new RuntimeException("postRequest -- Client protocol exception!", e);
        } catch (IOException e) {
            throw new RuntimeException("postRequest -- IO error!", e);
        } finally {
            post.releaseConnection();
        }
    }


    /**
     * get请求，参数放在map里
     *
     * @param url 请求地址
     * @param map 参数map
     * @return 响应
     */
    public static String getfileMap(String url, Map<String, String> map, String fileUrl, String fileName) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        List<NameValuePair> pairs = new ArrayList<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        CloseableHttpResponse response = null;
        String filestr = null;
        InputStream inputStream = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameters(pairs);
            HttpGet get = new HttpGet(builder.build());
            response = httpClient.execute(get);

            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                inputStream = response.getEntity().getContent();
                Header[] headers1 = response.getHeaders("Content-disposition");/*                for (int i = 0; i < headers1.length; i++) {
                    Header header = headers1[0];
                    String filenameheader = header.getValue();
                    String[] strings = filenameheader.split(";");
                    String strs = strings[1];
                    String str = strs.substring(11, strs.length() - 1);
                    String[] spstr = str.split("\\.");
                    String fileend = spstr[1];
                    log.info("fileend = " + fileend);
                }*/
                filestr = fileUrl + fileName + ".silk";
                File file1 = new File(filestr);
                if (!file1.exists()) {
                    file1.createNewFile();
                }
                OutputStream os = new FileOutputStream(file1);
                int read = 0;
                byte[] temp = new byte[1024 * 1024];

                while ((read = inputStream.read(temp)) > 0) {
                    byte[] bytes = new byte[read];
                    System.arraycopy(temp, 0, bytes, 0, read);
                    os.write(bytes);
                }
                os.flush();

            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return filestr;
    }

    /**
     * 发送POST请求（普通表单形式）
     *
     * @param url
     * @param header
     * @param parametersBody
     * @param timeout
     * @return
     */
    public static String postForm(String url, List<Header> header, List<BasicNameValuePair> parametersBody, Integer timeout) {
        HttpEntity entity = new UrlEncodedFormEntity(parametersBody, Charsets.UTF_8);
        return postRequest(url, "application/x-www-form-urlencoded", header, entity, timeout, true);
    }

    /**
     * 发送POST请求（JSON形式）
     *
     * @param url
     * @param header  请求header
     * @param json    请求body，json格式
     * @param timeout 访问超时时间，单位毫秒
     * @return
     */
    public static String postJSON(String url, List<Header> header, String json, Integer timeout, boolean isSafe) {
        StringEntity entity = new StringEntity(json, Charsets.UTF_8);
        return postRequest(url, "application/json; charset=utf-8", header, entity, timeout, isSafe);
    }

    /**
     * 发送POST请求
     *
     * @param url
     * @param mediaType
     * @param header
     * @param parametersBody
     * @param timeout
     * @return
     */
    private static String postRequest(String url, String mediaType, List<Header> header, HttpEntity parametersBody, Integer timeout, boolean isSafe) {
        log.info("请求地址：{}", url);
        log.info("请求方式：POST");
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-Type", mediaType);
        post.addHeader("Accept", "application/json");
        // 设置头参数
        if (CollectionUtils.isNotEmpty(header)) {
            for (Header item : header) {
                post.setHeader(item.getName(), item.getValue());
                log.info("请求Header：{}={}", item.getName(), item.getValue());
            }
        }
        // 请求参数
        post.setEntity(parametersBody);
        if (timeout != null && timeout.intValue() > 0) {
            RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
            post.setConfig(config);
        }

        try {
            log.info("请求参数：{}", EntityUtils.toString(parametersBody));
            CloseableHttpClient client = null;
            if(isSafe){
                client = HttpClientBuilder.create().build();
            }else{
                // 创建一个信任所有证书的SSLContext
                SSLContext sslContext = SSLContextBuilder.create()
                        .loadTrustMaterial(new TrustStrategy() {
                            @Override
                            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                                return true; // 忽略所有证书验证
                            }
                        })
                        .build();
                client = HttpClientBuilder.create().setSSLContext(sslContext)
                        .setSSLHostnameVerifier(new NoopHostnameVerifier())
                        .build();
            }
            HttpResponse response = client.execute(post);
            int code = response.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(response.getEntity());
            if (code >= 400) {
                throw new RuntimeException(result);
            }
            log.info("请求返回结果：{}", result);
            return result;
        } catch (ClientProtocolException e) {
            throw new RuntimeException("postRequest -- Client protocol exception!", e);
        } catch (IOException e) {
            throw new RuntimeException("postRequest -- IO error!", e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (KeyStoreException e) {
            throw new RuntimeException(e);
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        } finally {
            post.releaseConnection();
        }
    }
}
