package com.prolog.cs.biz.outbound.utils;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
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.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * httpClient4.5工具类
 *
 * @author daigaowei
 * @Date 2019年1月2日 下午5:13:00
 */
public class HttpClientUtils {
    enum HttpGetStatus {
        fail,ok
    }

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    private static RequestConfig requestConfig;

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

    /**
     * post请求-Map参数
     *
     * @param url    请求地址
     * @param params map参数
     * @return com.alibaba.fastjson.JSONObject
     * @Title postByForm
     * @author daigaowei
     * @Date 2019/6/17 15:34
     */
    public static JSONObject postByForm(String url, Map<String, String> params) {
        return postByForm(url, null, params);
    }

    /**
     * post请求-Map参数
     *
     * @param url     请求地址
     * @param headers 头信息
     * @param params  map参数
     * @return com.alibaba.fastjson.JSONObject
     * @Title postByForm
     * @author daigaowei
     * @Date 2019/6/17 15:34
     */
    public static JSONObject postByForm(String url, Map<String, String> headers, Map<String, String> params) {
        return postByForm(url, headers, params, false);
    }
    public static JSONObject postByForm(String url, Map<String, String> headers, Map<String, String> params, boolean returnHeader) {
        return postByForm(url, headers, params, null, returnHeader);
    }

    /**
     * post请求-Map参数
     *
     * @param url     请求地址
     * @param headers 头信息
     * @param params  map参数
     * @param proxy   代理服务器
     * @return com.alibaba.fastjson.JSONObject
     * @Title postByForm
     * @author daigaowei
     * @Date 2019/6/17 15:34
     */
    public static JSONObject postByForm(String url, Map<String, String> headers, Map<String, String> params, HttpHost proxy, boolean returnHeader) {
        CloseableHttpClient httpClient;
        if (url.startsWith("https")) {
            try {
                httpClient = new SSLClient();
            } catch (Exception e) {
                return null;
            }
        } else {
            httpClient = HttpClients.createDefault();
        }


        JSONObject body;

        logger.info("create httpPost:" + url);
        HttpPost httpPost = postForm(url, params);
        // 头信息
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPost.setHeader(key, headers.get(key));
            }
        }

        // 代理服务器
        if (proxy != null) {
            RequestConfig build = RequestConfig.copy(requestConfig).setProxy(proxy).build();
            httpPost.setConfig(build);
        }

        body = invoke(httpClient, httpPost);
        if (!returnHeader) {
            Object bodyObj = body.get("body");
            if (bodyObj != null) {
                body = JSON.parseObject(bodyObj.toString());
            }
        }

        return body;
    }

    /**
     * post请求-form表单String参数(name=Jack&sex=1&type=2)
     * Content-type:application/x-www-form-urlencoded
     *
     * @param url       请求地址
     * @param strParams form参数
     * @return com.alibaba.fastjson.JSONObject
     * @Title postByFormString
     * @author daigaowei
     * @Date 2019/6/17 15:32
     */
    public static JSONObject postByFormString(String url, String strParams) {
        return postByFormString(url, null, strParams);
    }

    /**
     * post请求-form表单String参数(name=Jack&sex=1&type=2)
     * Content-type:application/x-www-form-urlencoded
     *
     * @param url       请求地址
     * @param headers   头信息
     * @param strParams form参数
     * @return com.alibaba.fastjson.JSONObject
     * @Title postByFormString
     * @author daigaowei
     * @Date 2019/6/17 15:32
     */
    public static JSONObject postByFormString(String url, Map<String, String> headers, String strParams) {
        return postByFormString(url, headers, strParams, false);
    }

    public static JSONObject postByFormString(String url, Map<String, String> headers, String strParams, boolean returnHeader) {
        return postByFormString(url, headers, strParams, null, returnHeader);
    }

    public static JSONObject postByFormString(String url, Map<String, String> headers, String strParams, HttpHost proxy, boolean returnHeader) {
        // post请求返回结果
        CloseableHttpClient httpClient;
        if (url.startsWith("https")) {
            try {
                httpClient = new SSLClient();
            } catch (Exception e) {
                return null;
            }
        } else {
            httpClient = HttpClients.createDefault();
        }
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);

        try {
            if (null != strParams) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(strParams, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(entity);
            }

            // 头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.setHeader(key, headers.get(key));
                }
            }

            // 代理服务器
            if (proxy != null) {
                RequestConfig build = RequestConfig.copy(requestConfig).setProxy(proxy).build();
                httpPost.setConfig(build);
            }

            CloseableHttpResponse response = httpClient.execute(httpPost);

            // 解析服务器返回数据

            JSONObject jsonObject = parseResponse(response);
            if (returnHeader) {
                jsonResult = jsonObject;
            } else {
                Object body = jsonObject.get("body");
                if (body != null) {
                    jsonResult = JSON.parseObject(body.toString());
                }
            }
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * post请求-JSONObject参数
     *
     * @param url        请求地址
     * @param jsonParams json参数
     * @return com.alibaba.fastjson.JSONObject
     * @Title postByJson
     * @author daigaowei
     * @Date 2019/6/17 15:31
     */
    public static JSONObject postByJson(String url, String jsonParams) {
        return postByJson(url, null, jsonParams);
    }

    /**
     * post请求-JSONObject参数
     *
     * @param url        请求地址
     * @param headers    头信息
     * @param jsonParams JSONObject参数
     * @return com.alibaba.fastjson.JSONObject
     * @Title postByJson
     * @author daigaowei
     * @Date 2019/6/17 15:31
     */
    public static JSONObject postByJson(String url, Map<String, String> headers, String jsonParams) {
        return postByJson(url, headers, jsonParams, false);
    }

    public static JSONObject postByJson(String url, Map<String, String> headers, String jsonParams, boolean returnHeader) {
        return postByJson(url, headers, jsonParams, null, returnHeader);
    }

    public static JSONObject postByJson(String url, Map<String, String> headers, String jsonParams, HttpHost proxy, boolean returnHeader) {
        // post请求返回结果
        CloseableHttpClient httpClient;
        if (url.startsWith("https")) {
            try {
                httpClient = new SSLClient();
            } catch (Exception e) {
                return null;
            }
        } else {
            httpClient = HttpClients.createDefault();
        }
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        try {
            if (null != jsonParams) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParams.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }

            // 头信息
            if (headers != null) {
                headers.keySet().forEach(key -> httpPost.setHeader(key, headers.get(key)));
            }

            // 代理服务器
            if (proxy != null) {
                RequestConfig build = RequestConfig.copy(requestConfig).setProxy(proxy).build();
                httpPost.setConfig(build);
            }

            CloseableHttpResponse response = httpClient.execute(httpPost);

            if (response != null) {
                // 解析服务器返回数据
                JSONObject jsonObject = parseResponse(response);
                if (returnHeader) {
                    jsonResult = jsonObject;
                } else {
                    Object body = jsonObject.get("body");
                    if (body != null) {
                        jsonResult = JSON.parseObject(body.toString());
                    }
                }

            }
        } catch (IOException e) {
            assert jsonParams != null;
            logger.error("request params:{}", jsonParams);
            logger.error("post request url:{}, error:{}", url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * post请求-json字符串参数
     *
     * @param url        请求地址
     * @param jsonString json字符串
     * @return byte[]
     * @Title postByString
     * @author daigaowei
     * @Date 2019/6/17 15:29
     */
    public static byte[] postByString(String url, String jsonString) {
        return postByString(url, null, jsonString);
    }

    /**
     * post请求-json字符串参数
     *
     * @param url        请求地址
     * @param headers    头信息
     * @param jsonString json字符串
     * @return byte[]
     * @Title postByString
     * @author daigaowei
     * @Date 2019/6/17 15:29
     */
    public static byte[] postByString(String url, Map<String, String> headers, String jsonString) {
        return postByString(url, headers, jsonString, null);
    }

    public static byte[] postByString(String url, Map<String, String> headers, String jsonString, HttpHost proxy) {
        if (url == null || url.length() == 0) {
            return null;
        }
        CloseableHttpClient httpClient;
        if (url.startsWith("https")) {
            try {
                httpClient = new SSLClient();
            } catch (Exception e) {
                return null;
            }
        } else {
            httpClient = HttpClients.createDefault();
        }
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setEntity(new StringEntity(jsonString, "UTF-8"));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json;charset=UTF-8");

            // 头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.setHeader(key, headers.get(key));
                }
            }

            // 代理服务器
            if (proxy != null) {
                RequestConfig build = RequestConfig.copy(requestConfig).setProxy(proxy).build();
                httpPost.setConfig(build);
            }

            HttpResponse resp = httpClient.execute(httpPost);
            if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return null;
            }
            logger.info("======>>>entity:{}", resp.getEntity());
            return EntityUtils.toByteArray(resp.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * post请求-xml参数
     *
     * @param url    请求地址
     * @param params xml参数
     * @return com.alibaba.fastjson.JSONObject
     * @Title postByXml
     * @author daigaowei
     * @Date 2019/6/17 15:27
     */
    public static JSONObject postByXml(String url, String params) {
        return postByXml(url, null, params);
    }

    /**
     * post请求-xml参数
     *
     * @param url     请求地址
     * @param headers 头信息
     * @param params  xml参数
     * @return com.alibaba.fastjson.JSONObject
     * @Title postByXml
     * @author daigaowei
     * @Date 2019/6/17 15:27
     */
    public static JSONObject postByXml(String url, Map<String, String> headers, String params) {
        return postByXml(url, headers, params, false);
    }

    public static JSONObject postByXml(String url, Map<String, String> headers, String params, boolean returnHeader) {
        return postByXml(url, headers, params, null,returnHeader);
    }

    public static JSONObject postByXml(String url, Map<String, String> headers, String params, HttpHost proxy, boolean returnHeader) {
        CloseableHttpClient httpClient;
        if (url.startsWith("https")) {
            try {
                httpClient = new SSLClient();
            } catch (Exception e) {
                return null;
            }
        } else {
            httpClient = HttpClients.createDefault();
        }
        JSONObject body;

        logger.info("create httpPost:" + url);
        HttpPost httpPost = postFormXML(url, params);
        // 头信息
        if (headers != null) {
            headers.keySet().forEach(key -> httpPost.setHeader(key, headers.get(key)));
        }

        // 代理服务器
        if (proxy != null) {
            RequestConfig build = RequestConfig.copy(requestConfig).setProxy(proxy).build();
            httpPost.setConfig(build);
        }

        body = invoke(httpClient, httpPost);
        body = invoke(httpClient, httpPost);
        if (!returnHeader) {
            Object bodyObj = body.get("body");
            if (bodyObj != null) {
                body = JSON.parseObject(bodyObj.toString());
            }
        }

        return body;
    }

    /**
     * get请求-返回json
     *
     * @param url 请求地址
     * @return com.alibaba.fastjson.JSONObject
     * @Title getForJson
     * @author daigaowei
     * @Date 2019/6/17 15:26
     */
    public static JSONObject getForJson(String url) {
        return getForJson(url, null);
    }

    /**
     * get请求-返回json
     *
     * @param url     请求地址
     * @param headers 头信息
     * @return com.alibaba.fastjson.JSONObject
     * @Title getForJson
     * @author daigaowei
     * @Date 2019/6/17 15:26
     */
    public static JSONObject getForJson(String url, Map<String, String> headers) {
        return getForJson(url, headers, null, false);
    }

    public static JSONObject getForJson(String url, Map<String, String> headers, boolean returnHeader) {
        return getForJson(url, headers, null, returnHeader);
    }

    public static JSONObject getForJson(String url, Map<String, String> headers, HttpHost proxy, boolean returnHeader) {
        // get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient httpClient;
        if (url.startsWith("https")) {
            try {
                httpClient = new SSLClient();
            } catch (Exception e) {
                return null;
            }
        } else {
            httpClient = HttpClients.createDefault();
        }
        // 发送get请求
        HttpGet request = new HttpGet(url);

        try {
            // 头信息
            if (headers != null) {
                headers.keySet().forEach(key -> request.setHeader(key, headers.get(key)));
            }

            // 代理服务器
            if (proxy != null) {
                RequestConfig build = RequestConfig.copy(requestConfig).setProxy(proxy).build();
                request.setConfig(build);
            } else {
                request.setConfig(requestConfig);
            }

            CloseableHttpResponse response = httpClient.execute(request);
            // 解析服务器返回数据
            JSONObject jsonObject = parseResponse(response);
            if (returnHeader) {
                jsonResult = jsonObject;
            } else {
                Object body = jsonObject.get("body");
                if (body != null) {
                    jsonResult = JSON.parseObject(body.toString());
                }
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * get请求-返回String
     *
     * @param url 请求地址
     * @return java.lang.String [0]: 状态码 ok 成功, fail 失败 | [1]: 返回值
     * @Title getForString
     * @author daigaowei
     * @Date 2019/6/17 15:25
     */
    public static String[] getForString(String url) {
        return getForString(url, null);
    }

    /**
     * get请求-返回String
     *
     * @param url     请求地址
     * @param headers 头信息
     * @return java.lang.String
     * @Title getForString
     * @author daigaowei
     * @Date 2019/6/17 15:25
     */
    public static String[] getForString(String url, Map<String, String> headers) {
        return getForString(url, headers, null);
    }

    public static String[] getForString(String url, Map<String, String> headers, HttpHost proxy) {
        CloseableHttpClient httpClient;
        if (url.startsWith("https")) {
            try {
                httpClient = new SSLClient();
            } catch (Exception e) {
                return null;
            }
        } else {
            httpClient = HttpClients.createDefault();
        }

        CloseableHttpResponse response = null;
        String code = HttpGetStatus.fail.name();// 默认失败码，根据状态码返回更新值
        String body = null;
        String head = null;
        try {
            // 发送get请求
            HttpGet request = new HttpGet(url);
            // 头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    request.setHeader(key, headers.get(key));
                }
            }

            // 代理服务器
            if (proxy != null) {
                RequestConfig build = RequestConfig.copy(requestConfig).setProxy(proxy).build();
                request.setConfig(build);
            } else {
                request.setConfig(requestConfig);
            }

            response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK
                    && response.getStatusLine().getStatusCode() <= HttpStatus.SC_MULTI_STATUS) {
                code = HttpGetStatus.ok.name();// 成功
            }
            body = EntityUtils.toString(entity);
            head = JSON.toJSONString(response.getAllHeaders());
        } catch (IOException e) {
            logger.error("连接请求异常: ", e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                logger.error("关闭连接异常: ", e);
            }
        }
        return new String[]{code, body, head};
    }

    /**
     * 	下载文件
     *  @Title download
     *  @param url  文件地址
     *  @param filePath 文件保存路径（无后缀）
     *  @return boolean
     * 	@author daigaowei
     * 	@Date 2020/11/15 18:50
     */
    public static String download(String url, String filePath) {
        CloseableHttpClient httpClient;
        if (url.startsWith("https")) {
            try {
                httpClient = new SSLClient();
            } catch (Exception e) {
                return null;
            }
        } else {
            httpClient = HttpClients.createDefault();
        }

        CloseableHttpResponse response = null;
        try {
            // 发送get请求
            HttpGet request = new HttpGet(url);
            response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            String extension = FileUtil.extName(url);
            String localPath = filePath + "." + extension;
            File file = FileUtil.file(localPath);
            FileOutputStream os = new FileOutputStream(file);
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = is.read(buffer)) != -1) {
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                os.write(buffer, 0, len);
            }
            //关闭输入流
            is.close();
            // 完毕，关闭所有链接
            os.flush();
            os.close();
            return localPath;
        } catch (IOException e) {
            logger.error("连接请求异常: ", e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                logger.error("关闭连接异常: ", e);
            }
        }
        return null;
    }

    /**
     * 组装form参数请求
     *
     * @param @param  url
     * @param @param  params
     * @param @return
     * @return HttpPost
     * @Title postForm
     * @author daigaowei
     * @Date 2019年1月2日 下午5:17:58
     */
    private static HttpPost postForm(String url, Map<String, String> params) {

        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nameValuePairs = new ArrayList<>();

        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
        }

        try {
            logger.info("set utf-8 form entity to httpPost");
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return httpPost;
    }

    /**
     * 组装xml参数请求
     *
     * @param @param  url
     * @param @param  params
     * @param @return
     * @return HttpPost
     * @Title postFormXML
     * @author daigaowei
     * @Date 2019年1月2日 下午5:18:19
     */
    private static HttpPost postFormXML(String url, String params) {

        HttpPost httpPost = new HttpPost(url);

        try {
            logger.info("set utf-8 form entity to httpPost");

            StringEntity entity = new StringEntity(params);
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return httpPost;
    }

    /**
     * post请求 - 返回String
     * @param requestUrl
     * @param formTexts
     * @return
     */
    public static String sendPost(String requestUrl, Map<String, String> formTexts){
        return sendPost(requestUrl, null, formTexts);
    }

    public static String sendPost(String requestUrl, Map<String, String> requestHeader, Map<String, String> formTexts){
        return sendPost(requestUrl, requestHeader, formTexts, null, null, null);
    }

    public static String sendPost(String requestUrl, Map<String, String> requestHeader, Map<String, String> formTexts, Map<String, String> files, String requestEncoding, String responseEncoding) {
        OutputStream out = null;
        BufferedReader reader = null;
        StringBuilder result = new StringBuilder();
        try {
            if (requestUrl == null || requestUrl.isEmpty()) {
                return result.toString();
            }
            URL realUrl = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Map.Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            if (requestEncoding == null || requestEncoding.isEmpty()) {
                requestEncoding = "UTF-8";
            }
            if (responseEncoding == null || responseEncoding.isEmpty()) {
                responseEncoding = "UTF-8";
            }
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Map.Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            if (files == null || files.size() == 0) {
                connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                out = new DataOutputStream(connection.getOutputStream());
                if (formTexts != null && formTexts.size() > 0) {
                    StringBuilder formData = new StringBuilder();
                    for (Map.Entry<String, String> entry : formTexts.entrySet()) {
                        formData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                    }
                    formData = new StringBuilder(formData.substring(0, formData.length() - 1));
                    out.write(formData.toString().getBytes(requestEncoding));
                }
            } else {
                String boundary = "-----------------------------" + new Date().getTime();
                connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);
                out = new DataOutputStream(connection.getOutputStream());
                if (formTexts != null && formTexts.size() > 0) {
                    StringBuilder sbFormData = new StringBuilder();
                    for (Map.Entry<String, String> entry : formTexts.entrySet()) {
                        sbFormData.append("--").append(boundary).append("\r\n");
                        sbFormData.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"\r\n\r\n");
                        sbFormData.append(entry.getValue()).append("\r\n");
                    }
                    out.write(sbFormData.toString().getBytes(requestEncoding));
                }
                for (Map.Entry<String, String> entry : files.entrySet()) {
                    String fileName = entry.getKey();
                    String filePath = entry.getValue();
                    if (fileName == null || fileName.isEmpty() || filePath == null || filePath.isEmpty()) {
                        continue;
                    }
                    File file = new File(filePath);
                    if (!file.exists()) {
                        continue;
                    }
                    out.write(("--" + boundary + "\r\n").getBytes(requestEncoding));
                    out.write(("Content-Disposition: form-data; name=\"" + fileName + "\"; filename=\"" + file.getName() + "\"\r\n").getBytes(requestEncoding));
                    out.write(("Content-Type: application/x-msdownload\r\n\r\n").getBytes(requestEncoding));
                    DataInputStream in = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                    out.write(("\r\n").getBytes(requestEncoding));
                }
                out.write(("--" + boundary + "--").getBytes(requestEncoding));
            }
            out.flush();
            out.close();
            out = null;
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), responseEncoding));
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！");
            e.printStackTrace();
            logger.info("发送POST请求出现异常, error = {}", e.toString());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }


    /**
     * 调用请求，调用响应解析
     *
     * @param @param  httpclient
     * @param @param  httpPost
     * @param @return
     * @return JSONObject
     * @Title invoke
     * @author daigaowei
     * @Date 2019年1月2日 下午5:20:06
     */
    private static JSONObject invoke(CloseableHttpClient httpclient, HttpUriRequest httpPost) {

        HttpResponse response = sendRequest(httpclient, httpPost);

        return parseResponse(response);
    }

    /**
     * 执行请求
     *
     * @param @param  httpclient
     * @param @param  httpost
     * @param @return
     * @return HttpResponse
     * @Title sendRequest
     * @author daigaowei
     * @Date 2019年1月2日 下午5:20:31
     */
    private static HttpResponse sendRequest(CloseableHttpClient httpclient, HttpUriRequest httpPost) {
        logger.info("execute post...");
        HttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 解析响应
     *
     * @param @param  response
     * @param @return
     * @return JSONObject
     * @Title parseResponse
     * @author daigaowei
     * @Date 2019年1月2日 下午5:20:48
     */
    private static JSONObject parseResponse(HttpResponse response) {
        // 读取服务器返回过来的json字符串数据
        logger.info("get response from http server..");
        Header[] allHeaders = response.getAllHeaders();

        HttpEntity entity = response.getEntity();
        logger.info("response status: " + response.getStatusLine());
        String body;
        JSONObject json = new JSONObject();
        json.put("header", allHeaders);
        try {
            body = EntityUtils.toString(entity, "utf-8");
            logger.info(body);
//            json = JSONObject.parseObject(body);
            json.put("body", body);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        // 把json字符串转换成json对象
        return json;
    }

}