EciHttpUtil.java 9.33 KB
package com.pashanhoo.common;

import com.alibaba.fastjson.JSONObject;
import com.pashanhoo.qys.service.SysFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class EciHttpUtil {

    private static Logger logger = LoggerFactory.getLogger(EciHttpUtil.class);
    @Value("${app.AppToken}")
    private  String appToken;
    @Value("${app.AppSecret}")
    private  String appSecret;

    @Value("${app.hostUrl}")
    private  String hostUrl;

    @Value("${app.eciPath}")
    private String eciPath;
    @Autowired
    private SysFileService sysFileService;




    public  Map doPostForNew(String url, String params) {
        logger.info("http request url:" + url);
        logger.info("http request url:" + params);
        PrintWriter out = null;
        BufferedReader in = null;
        Map jsonObject = new HashMap();
        try{
            URL url1=new URL(url);
            HttpURLConnection conn= (HttpURLConnection) url1.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept","*/*");
            conn.setRequestProperty("connection","Keep-Alive");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            //x-qys-signature生成方式:Md5(AppToken + AppSecret + timestamp),获取32位小写值
            long times=System.currentTimeMillis();
            String unSignature = appToken + appSecret + times;
            String signature = MD5Util.getMD5(unSignature);
            conn.setRequestProperty("x-qys-accesstoken", appToken);
            conn.setRequestProperty("x-qys-signature", signature);
            conn.setRequestProperty("x-qys-timestamp", String.valueOf(times));

            logger.info("x-qys-accesstoken==="+appToken);
            logger.info("x-qys-signature==="+signature);
            logger.info("x-qys-timestamp==="+System.currentTimeMillis());


            out=new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
            out.print(params);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String result="";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            jsonObject = JSONObject.parseObject(result, Map.class);
        }catch (Exception ex){
            logger.info("发送 POST 请求出现异常!" + ex);
            ex.printStackTrace();
        }finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return jsonObject;
    }

    public  Map doGetForNew(String url) {
        logger.info("http request url:" + url);
        BufferedReader in = null;
        String result = "";
        Map jsonObject = new HashMap();
        try{
            URL url1=new URL(url);
            HttpURLConnection conn= (HttpURLConnection) url1.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("accept","*/*");
            conn.setRequestProperty("connection","Keep-Alive");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setDoInput(true);
            conn.setDoOutput(false);
            //x-qys-signature生成方式:Md5(AppToken + AppSecret + timestamp),获取32位小写值
            long times=System.currentTimeMillis();
            String unSignature = appToken +appSecret + times;
            String signature = MD5Util.getMD5(unSignature);
            conn.setRequestProperty("x-qys-accesstoken", appToken);
            conn.setRequestProperty("x-qys-signature", signature);
            conn.setRequestProperty("x-qys-timestamp", String.valueOf(times));

            logger.info("x-qys-accesstoken==="+appToken);
            logger.info("x-qys-signature==="+signature);
            logger.info("x-qys-timestamp==="+System.currentTimeMillis());

            conn.connect();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            jsonObject = JSONObject.parseObject(result, Map.class);
        }catch (Exception ex){
            logger.info("发送 POST 请求出现异常!" + ex);
            ex.printStackTrace();
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return jsonObject;
    }



    /**
     * 文件下载
     *
     * @param documentId 合同文档ID
     * @return
     */
    public  String[] download(String documentId,String bh,String htlx,String areacode) {
        String url = hostUrl + "/document/download" + "?documentId=" + documentId;
        InputStream in = null;
        String localPath = "";
        String minioPath="";
        OutputStream out = null;
        String backUrl[]=new String[2];
        try{
            URL url1=new URL(url);
            HttpURLConnection conn= (HttpURLConnection) url1.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("accept","*/*");
            conn.setRequestProperty("connection","Keep-Alive");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            long times=System.currentTimeMillis();
            //x-qys-signature生成方式:Md5(AppToken + AppSecret + timestamp),获取32位小写值
            String unSignature = appToken + appSecret + times;
            String signature = MD5Util.getMD5(unSignature);
            conn.setRequestProperty("x-qys-accesstoken", appToken);
            conn.setRequestProperty("x-qys-signature", signature);
            conn.setRequestProperty("x-qys-timestamp", String.valueOf(times));

            logger.info("x-qys-accesstoken==="+appToken);
            logger.info("x-qys-signature==="+signature);
            logger.info("x-qys-timestamp==="+System.currentTimeMillis());

            conn.connect();
            in =conn.getInputStream();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
            String dateDir = simpleDateFormat.format(new Date());
           File savePath = new File(eciPath+"ECI\\"+areacode+"\\"+ htlx+dateDir+bh);
            if (!savePath.exists()) {
                savePath.mkdirs();
            }
            File filePath = new File(savePath + "\\" + documentId+".ofd");
            if (!filePath.exists()){
                filePath.createNewFile();
            }
            byte[] bytes = cloneInputStream(in);
            InputStream fileInputStream = new ByteArrayInputStream(bytes);
            out = new FileOutputStream(filePath);
            byte[] buffer = new byte[4096];
            int readLength = 0;
            while ((readLength = fileInputStream.read(buffer)) != -1) {
                out.write(buffer, 0, readLength);
            }
            out.flush();
            localPath = filePath.getAbsolutePath();
            backUrl[0]=localPath;

            InputStream newInputStream = new ByteArrayInputStream(bytes);
            MultipartFile multipartFile = new MockMultipartFile(
                    "File", documentId+".ofd",
                    "text/plain",
                    newInputStream);
            String miniofilePath=areacode+"/"+ htlx+dateDir+bh+"/"+documentId+".ofd";
            minioPath=sysFileService.uploadFileMinio(multipartFile,miniofilePath);
            backUrl[1]=minioPath;
        }catch (Exception ex){
            logger.info("发送 POST 请求出现异常!" + ex);
            ex.printStackTrace();
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
                if(out != null) {
                    out.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return backUrl;
    }

    /**
     * 将流存在缓存流中,这样可以重复使用
     * @param input
     * @return
     */
    private static  byte[] cloneInputStream(InputStream input) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            baos.close();
            input.close();
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }







}