package com.cn.weisou.common;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class DownloadUtil {
/**
* 发送get请求, 下载图片
*
* @param url
* 路径
* @return
*/
public static void httpGetImg(CloseableHttpClient client, String imgUrl, String savePath) {
// 发送get请求
HttpGet request = new HttpGet(imgUrl);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();
// 设置请求头
request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");
request.setConfig(requestConfig);
try {
CloseableHttpResponse response = client.execute(request);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
FileUtils.copyInputStreamToFile(in, new File(savePath));
System.out.println("下载图片成功:" + imgUrl);
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
request.releaseConnection();
}
}
// 自己写一个FileUitl工具类
public static byte[] readToByte(File file) throws IOException {
long length = file.length();
if (length > Integer.MAX_VALUE)
throw new IOException("file too large");
byte[] b = null;
InputStream in = null;
try {
b = new byte[(int) length];
in = new FileInputStream(file);
int offset = 0, nRead = 0;
while (offset < b.length && (nRead = in.read(b, offset, b.length - offset)) != -1)
offset += nRead;
} catch (Exception e) {
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
return b;
}
/**
* 根据文件,进行压缩,批量下载
*
* @param response
* @param files
* @throws Exception
*/
public static void downloadBatchByFile(HttpServletResponse response, Map<String, byte[]> files, String zipName) {
try {
// 设置响应消息头
response.setContentType("application/x-msdownload");
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(zipName, "utf-8"));
// 输出、输入流
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
BufferedOutputStream bos = new BufferedOutputStream(zos);
for (Entry<String, byte[]> entry : files.entrySet()) {
String fileName = entry.getKey(); // 每个zip文件名
byte[] file = entry.getValue(); // 这个zip文件的字节
BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file));
zos.putNextEntry(new ZipEntry(fileName));
int len = 0;
byte[] buf = new byte[10 * 1024];
while ((len = bis.read(buf, 0, buf.length)) != -1) {
bos.write(buf, 0, len);
}
bis.close();
bos.flush();
}
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
// 文件名-字节数组的形式
Map<String, byte[]> files = new HashMap<String, byte[]>();
// 获取文件后缀
String imgType = "png";
// 获取文件名,key
for (int i = 0; i < 10; i++) {
// 文件名称
String packageName = i + "." + imgType;
// 文件路径
File file = new File("E:/AA/0.jpg");
System.out.println(file.length());
// File转byte[ ]
// 二进制数据,value
byte[] f = DownloadUtil.readToByte(file);
files.put(packageName, f);
}
// 设置下载的压缩包名
String zipName = new Date().getTime() + ".zip";
// // 根据文件,进行压缩,批量下载
// if (files.size() > 0) {
// DownloadUtil.downloadBatchByFile(response, files, zipName);
// }
}
}