package org.x3.cloud.file.util;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
/**
* created by Rock-Ayl on 2019-7-15
* 該工具類就一個作用,將靜態文件下載到服務器本地目錄
*/
public class HttpDownloadUtils {
protected static Logger logger = LoggerFactory.getLogger(HttpDownloadUtils.class);
//文件寫入時緩衝區大小
public static final int cache = 10 * 1024;
//是否爲windows系統
public static boolean isWindows = false;
//默認下載目錄
public static String dir = "/Users/";
/**
* 根據操作系統初始化盤符
*/
static {
//系統
String system = System.getProperty("os.name");
//判空
if (StringUtils.isNotEmpty(system)) {
//判斷是否爲windows
if (system.toLowerCase().contains("windows")) {
isWindows = true;
dir = "C:\\";
}
}
}
/**
* 根據url下載文件,保存到filepath中
*
* @param url 文件URL
* @param filePath 文件下載地址,可爲null
* @return 下載是否成功
*/
public static boolean download(String url, String filePath) {
try {
//創建連接對象
HttpClient client = new DefaultHttpClient();
//URL對象
HttpGet httpget = new HttpGet(url);
//請求URL,獲取響應
HttpResponse response = client.execute(httpget);
//響應實體
HttpEntity entity = response.getEntity();
//文件流
InputStream is = entity.getContent();
//判空
if (StringUtils.isEmpty(filePath)) {
//根據請求生成生成文件地址
filePath = getFilePath(response);
}
//獲取文件對象
File file = new File(filePath);
//創建目錄
file.getParentFile().mkdirs();
//輸出流對象
FileOutputStream fileOut = new FileOutputStream(file);
/**
* 根據實際運行效果 設置緩衝區大小
*/
byte[] buffer = new byte[cache];
int ch;
while ((ch = is.read(buffer)) != -1) {
//寫入
fileOut.write(buffer, 0, ch);
}
//清除
is.close();
fileOut.flush();
fileOut.close();
return true;
} catch (Exception e) {
logger.error("下載靜態文件時出錯:{}", e);
return false;
}
}
/**
* 獲取response要下載的文件的默認路徑
*
* @param response
* @return
*/
private static String getFilePath(HttpResponse response) {
//文件目錄
String filepath = dir;
//從響應中獲取文件名
String filename = getFileNameFromResponse(response);
//判空
if (StringUtils.isNotEmpty(filename)) {
//用請求的
filepath += filename;
} else {
//用隨機的
filepath += getRandomFileName();
}
return filepath;
}
/**
* 從response的header中Content-Disposition中的filename值
*
* @param response
* @return
*/
private static String getFileNameFromResponse(HttpResponse response) {
//獲取Content-Disposition
Header contentHeader = response.getFirstHeader("Content-Disposition");
//初始化name
String filename = null;
//判空
if (contentHeader != null) {
HeaderElement[] values = contentHeader.getElements();
if (values.length == 1) {
NameValuePair param = values[0].getParameterByName("filename");
if (param != null) {
try {
filename = param.getValue();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return filename;
}
/**
* 獲取一個基於當前時間戳的隨機文件名
*
* @return
*/
private static String getRandomFileName() {
return String.valueOf(System.currentTimeMillis());
}
}