EciHttpUtil.java 7.37 KB
package com.thinkgem.jeesite.modules.eci.utils;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.exception.BussException;
import com.thinkgem.jeesite.common.utils.JsonUtil;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class EciHttpUtil {

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

    /**
     * post请求接口地址
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String doPost(String url, Map params) {

        logger.info("http request url:" + url);
        logger.info("http request data:" + JsonUtil.toJsonString(params));

        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> urlParameters = Lists.newArrayList();
        String result = null;
        //创建通道
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            if (params != null && params.size() > 0) {
                Iterator<String> it = params.keySet().iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    urlParameters.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(urlParameters, "utf-8"));
            }
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
            //x-qys-signature生成方式:Md5(AppToken + AppSecret + timestamp),获取32位小写值
            String unSignature = Global.ECI_APP_TOKEN + Global.ECI_APP_SECRET + System.currentTimeMillis();
            String signature = MD5Util.getMD5(unSignature);

            httpPost.setHeader("x-qys-signature", signature);

            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                result = EntityUtils.toString(entity, "utf-8");
            } else {
                throw new BussException("返回状态码:" + code);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
            try {
                response.close();
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * get请求接口地址
     *
     * @param url
     * @param
     * @return
     * @throws Exception
     */
    public static String doGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        String result = null;
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            httpGet.setHeader("Content-Type", "application/json;charset=utf-8");
            //x-qys-signature生成方式:Md5(AppToken + AppSecret + timestamp),获取32位小写值
            String unSignature = Global.ECI_APP_TOKEN + Global.ECI_APP_SECRET + System.currentTimeMillis();
            String signature = MD5Util.getMD5(unSignature);
            httpGet.setHeader("x-qys-signature", signature);
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                result = EntityUtils.toString(entity, "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpGet.releaseConnection();
            try {
                response.close();
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 文件下载
     *
     * @param documentId 合同文档ID
     * @return
     */
    public static String download(String documentId) {

        String url = Global.ECI_HOST + "/document/download" + "?documentId=" + documentId;

        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        OutputStream out = null;
        InputStream in = null;
        String absolutePath = null;
        try {
            httpGet.setHeader("Content-Type", "application/json;charset=utf-8");
            //x-qys-signature生成方式:Md5(AppToken + AppSecret + timestamp),获取32位小写值
            String unSignature = Global.ECI_APP_TOKEN + Global.ECI_APP_SECRET + System.currentTimeMillis();
            String signature = MD5Util.getMD5(unSignature);
            httpGet.setHeader("x-qys-signature", signature);
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            in = entity.getContent();
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                long length = entity.getContentLength();
                if (length > 0) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dddd");
                    String dateDir = simpleDateFormat.format(new Date());
                    // File file = new File("E:\\ECI\\OFD\\" + dateDir + "\\" + documentId + ".ofd");
                    File savePath = new File("E:\\ECI\\OFD\\" + dateDir);
                    if (!savePath.exists()) {
                        savePath.mkdirs();
                    }
                    File filePath = new File(savePath + "\\" + documentId+".ofd");
                    if (!filePath.exists()){
                        filePath.createNewFile();
                    }

                    out = new FileOutputStream(filePath);
                    byte[] buffer = new byte[4096];
                    int readLength = 0;
                    while ((readLength = in.read(buffer)) != -1) {
                        // byte[] bytes = new byte[readLength];
                        // System.arraycopy(buffer, 0, bytes, 0, readLength);
                        out.write(buffer, 0, readLength);
                    }
                    absolutePath = filePath.getAbsolutePath();
                    out.flush();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpGet.releaseConnection();
            try {
                response.close();
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return absolutePath;
    }

}