Quellcode durchsuchen

2022-12-29 联调后使用https协议通信并取消传输图片

milo vor 1 Jahr
Ursprung
Commit
4825eac29d

+ 274 - 0
code/robot2ips/src/main/java/com/sunwin/robot2ips/util/FtpUtils.java

@@ -0,0 +1,274 @@
+package com.sunwin.robot2ips.util;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.net.ftp.FTPClient;
+import org.apache.commons.net.ftp.FTPReply;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import sun.misc.BASE64Encoder;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.SocketException;
+import java.net.URLEncoder;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.UUID;
+
+/**
+ * FTP服务工具类
+ *
+ * @author machao
+ * @version 1.0
+ * @date 2021/6/21 15:54
+ */
+@Component
+public class FtpUtils {
+
+    private static final Logger logger = LoggerFactory.getLogger(FtpUtils.class);
+
+
+    private static String host;
+
+    private static String account;
+
+    private static String password;
+
+    private static int port;
+
+    @Value("${ftp.host}")
+    public void setHost(String host) {
+        this.host = host;
+    }
+
+    @Value("${ftp.account}")
+    public void setAccount(String account) {
+        this.account = account;
+    }
+
+    @Value("${ftp.password}")
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    @Value("${ftp.port}")
+    public void setPort(int port) {
+        this.port = port;
+    }
+
+
+    //图片目录
+    private static final String picFilePath = "/pic";
+
+    //视频目录(暂未开放接口)
+    private static final String videoFilePath = "/video";
+
+    //一般文件目录(excel、doc...etc)
+    private static final String filePath = "/file";
+
+
+    /**
+     * FTP图片地址转base64
+     *
+     * @param: filePath
+     * @author machao
+     * @date: 2021/7/6 15:43
+     */
+    public static String addrToBase64(String filePath) {
+        if (StringUtils.isEmpty(filePath)) {
+            return null;
+        }
+        String[] split = filePath.split("/");
+        String fileName = split[split.length - 1];
+        FTPClient ftpClient = null;
+        byte[] buffer = null;
+        String result = null;
+        try {
+            ftpClient = getFTPClient();
+            String newPath = new String(filePath.getBytes("GBK"), "ISO-8859-1");
+            // ftp文件获取文件
+            InputStream retrieveFileStream = ftpClient.retrieveFileStream(newPath);
+            if (null == retrieveFileStream) {
+                throw new FileNotFoundException(fileName);
+            }
+            ByteArrayOutputStream bos = new ByteArrayOutputStream();
+            int length;
+            byte[] buf = new byte[2048];
+            while (-1 != (length = retrieveFileStream.read(buf, 0, buf.length))) {
+                bos.write(buf, 0, length);
+            }
+            ByteArrayInputStream fis = new ByteArrayInputStream(bos.toByteArray());
+            bos.flush();
+            bos.close();
+            buffer = new byte[fis.available()];
+            int offset = 0;
+            int numRead = 0;
+            while (offset < buffer.length && (numRead = fis.read(buffer, offset, buffer.length - offset)) >= 0) {
+                offset += numRead;
+            }
+            if (offset != buffer.length) {
+                throw new IOException("Could not completely read file ");
+            }
+            fis.close();
+            BASE64Encoder base64Encoder = new BASE64Encoder();
+            result = base64Encoder.encode(buffer);
+            retrieveFileStream.close();
+            ftpClient.logout();
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            disconnect(ftpClient);
+        }
+        return result;
+    }
+
+
+    /**
+     * 删除文件
+     *
+     * @param: filePath 文件路径包含文件名
+     * @return:
+     * @author machao
+     * @date: 2021/7/6 11:39
+     */
+    public static boolean deleteFile(String filePath) {
+        if (StringUtils.isEmpty(filePath) || !filePath.contains("/")) {
+            return false;
+        }
+        boolean isAppend = false;
+        String[] split = filePath.split("/");
+        String fileName = split[split.length - 1];
+        filePath = filePath.replace("/" + fileName, "").trim();
+        FTPClient ftpClient = null;
+        try {
+            ftpClient = getFTPClient();
+            filePath = new String(filePath.getBytes("GBK"), "iso-8859-1");
+            ftpClient.changeWorkingDirectory(filePath);
+            fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
+            ftpClient.dele(fileName);
+            ftpClient.logout();
+            isAppend = true;
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            disconnect(ftpClient);
+        }
+        return isAppend;
+    }
+
+
+    /**
+     * 下载文件到浏览器
+     *
+     * @param: filePath 文件路径
+     * @author machao
+     * @date: 2021/6/25 10:47
+     */
+    public static void download(String filePath, HttpServletResponse response) {
+        String[] strs = filePath.split("/");
+        String downloadFile = strs[strs.length - 1];
+        InputStream is = null;
+        BufferedInputStream bis = null;
+        FTPClient ftpClient = null;
+        try {
+            // 设置文件ContentType类型,这样设置,会自动判断下载文件类型
+            response.setContentType("application/x-msdownload");
+            // 设置文件头:最后一个参数是设置下载的文件名并编码为UTF-8
+            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadFile, "UTF-8"));
+            // 建立连接
+            ftpClient = getFTPClient();
+
+            String newPath = new String(filePath.getBytes("GBK"), "ISO-8859-1");
+            // ftp文件获取文件
+            is = ftpClient.retrieveFileStream(newPath);
+            bis = new BufferedInputStream(is);
+            OutputStream out = response.getOutputStream();
+            byte[] buf = new byte[1024];
+            int len = 0;
+            while ((len = bis.read(buf)) > 0) {
+                out.write(buf, 0, len);
+            }
+            out.flush();
+            out.close();
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            disconnect(ftpClient);
+            try {
+                if (is != null) {
+                    try {
+                        is.close();
+                    } catch (IOException e) {
+                        e.printStackTrace();
+                    }
+                }
+                if (bis != null) {
+
+                    bis.close();
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+                logger.error("输入流关闭失败!");
+            }
+        }
+    }
+
+
+    /**
+     * 与FTP服务器建立连接
+     */
+    public static FTPClient getFTPClient() {
+        FTPClient ftpClient = new FTPClient();
+        try {
+            ftpClient = new FTPClient();
+            //设置连接超时时间:5s
+            ftpClient.setConnectTimeout(5 * 1000);
+
+            ftpClient.connect(host, port);
+            ftpClient.login(account, password);
+
+            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
+                logger.info("未连接到FTP,用户名或密码错误。");
+                ftpClient.disconnect();
+                return null;
+            }
+            ftpClient.enterLocalPassiveMode();
+//            ftpClient.setControlEncoding("GBK");
+
+            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
+            //设置缓冲池大小
+            ftpClient.setBufferSize(1024 * 1024 * 10);
+
+        } catch (SocketException e) {
+            e.printStackTrace();
+            logger.error("FTP的IP地址可能错误,请正确配置。");
+        } catch (IOException e) {
+            e.printStackTrace();
+            logger.error("FTP的端口错误,请正确配置。");
+        }
+        return ftpClient;
+    }
+
+
+    /**
+     * 断开连接
+     *
+     * @param ftpClient
+     * @throws Exception
+     */
+    public static void disconnect(FTPClient ftpClient) {
+        if (ftpClient != null && ftpClient.isConnected()) {
+            try {
+                ftpClient.disconnect();
+                //logger.info("已关闭连接");
+            } catch (IOException e) {
+                logger.error("没有关闭连接");
+                e.printStackTrace();
+            }
+        }
+    }
+
+}

+ 77 - 0
code/robot2ips/src/main/java/com/sunwin/robot2ips/util/HttpsUtils.java

@@ -0,0 +1,77 @@
+package com.sunwin.robot2ips.util;
+
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.net.HttpURLConnection;
+import java.net.URL;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSessionContext;
+
+public class HttpsUtils {
+    /**
+     * 发送HTTPS请求
+     * @param toURL 请求地址
+     * @param data 请求参数
+     * @param dateType 参数类型,“JSON”,other
+     * @return
+     * @throws Exception
+     */
+    public static String HttpsPostUtil(String toURL, String data,String dateType)
+            throws Exception {
+        StringBuffer bs = new StringBuffer();
+
+        //  直接通过主机认证
+        HostnameVerifier hv = new HostnameVerifier() {
+            @Override
+            public boolean verify(String arg0, SSLSession arg1) {
+                return true;
+            }
+        };
+        //  配置认证管理器
+        javax.net.ssl.TrustManager[] trustAllCerts = {new TrustAllTrustManager()};
+        SSLContext sc = SSLContext.getInstance("SSL");
+        SSLSessionContext sslsc = sc.getServerSessionContext();
+        sslsc.setSessionTimeout(0);
+        sc.init(null, trustAllCerts, null);
+        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
+        //  激活主机认证
+        HttpsURLConnection.setDefaultHostnameVerifier(hv);
+        URL url = new URL(toURL);
+        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
+        connection.setConnectTimeout(30000);
+        connection.setReadTimeout(30000);
+        connection.setDoOutput(true);
+        if("JSON".equalsIgnoreCase(dateType)){
+            connection.setRequestProperty("Content-Type","application/json;chert=UTF-8");
+        }else{
+            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
+        }
+        OutputStreamWriter out = new OutputStreamWriter(
+                connection.getOutputStream(), "UTF-8");
+        out.write(data);
+        out.flush();
+        out.close();
+        connection.connect();
+        int code = ((HttpURLConnection) connection).getResponseCode();
+        InputStream is =  null;
+        if (code == 200) {
+            is = connection.getInputStream(); // 得到网络返回的正确输入流
+        } else {
+            is = ((HttpURLConnection) connection).getErrorStream(); // 得到网络返回的错误输入流
+        }
+        BufferedReader buffer = new BufferedReader(new InputStreamReader(is,"UTF-8"));
+
+        String l = null;
+        while ((l = buffer.readLine()) != null) {
+            bs.append(l);
+        }
+        //return bs.toString();
+        return String.valueOf(bs);
+    }
+}

+ 23 - 0
code/robot2ips/src/main/java/com/sunwin/robot2ips/util/TrustAllTrustManager.java

@@ -0,0 +1,23 @@
+package com.sunwin.robot2ips.util;
+
+
+public class TrustAllTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
+
+    @Override
+    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
+        return null;
+    }
+
+    @Override
+    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
+            throws java.security.cert.CertificateException {
+        return;
+    }
+
+    @Override
+    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
+            throws java.security.cert.CertificateException {
+        return;
+    }
+
+}