package com.sercurityControl.proteam.util; import lombok.extern.slf4j.Slf4j; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import static org.springframework.util.FileCopyUtils.BUFFER_SIZE; @Slf4j public class DownLoadUtil { public static void downFile(String filePath,String fileType){ try{ String savePath = "/data/vmw/queryDownload/"; // linux 系统路径 String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { savePath = "D://files/queryDownload/"; } // 构造URL URL url = new URL(filePath); // 打开连接 URLConnection con = url.openConnection(); //设置请求超时为20s con.setConnectTimeout(20 * 1000); //文件路径不存在 则创建 File sf = new File(savePath); if (!sf.exists()) { sf.mkdirs(); } //jdk 1.7 新特性自动关闭 try (InputStream in = con.getInputStream(); OutputStream out = new FileOutputStream(sf.getPath() + "\\" + "filename."+fileType)) { //创建缓冲区 byte[] buff = new byte[1024]; int n; // 开始读取 while ((n = in.read(buff)) >= 0) { out.write(buff, 0, n); } } catch (Exception e) { e.printStackTrace(); } }catch (Exception e){ log.error(e.toString(),e); } } public static void DownLoadFile(String url ,String fileType){ BufferedReader in=null; try{ URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } Date date = new Date(); SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMddhhmmss"); InputStream inputStream = connection.getInputStream(); String videoFiles = "/data/vmw/queryDownload/"; // linux 系统路径 String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { videoFiles = "D://files/queryDownload/"; } String filesPath = videoFiles + "pictureWebFile/" + dateFormat.format(date) + "." + fileType; File saveFile = new File(filesPath); //生成文件夹 if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); } FileOutputStream outputStream = new FileOutputStream(saveFile); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; System.out.println("Receiving data..."); while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } System.out.println("Data received."); outputStream.close(); inputStream.close(); // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); }catch (Exception e){ System.out.println("发送GET请求出现异常!" + e); log.error(e.toString(),e); } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } } }