前言
- 这篇是上篇的后续,主要是编写一个简单的http下载工具,使用的wget库,这周就简单写一写,下几周会重点说说,真实下载处理及查表优化。
注意
代码
pom配置
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>wget</artifactId>
<version>1.4.9</version>
</dependency>
通用下载工具
//下载文件
public static String downToLocal(String url,String fileBasePath, String fileName, String extName, JSONObject headers) throws Exception {
Logger logger = LoggerFactory.getLogger(DownloadFileTool.class);
String name = (fileName + "." + extName).toLowerCase();
String filePath = fileBasePath + name;
String downUrl = url;
File file = new File(filePath);
try {
URL downUrll = new URL(downUrl);
DownloadInfo info = new DownloadInfo(downUrll);
info.setUserAgent("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
if (headers != null) {
info.setReferer(new URL(headers.get("Referer").toString()));
}
WGet get = new WGet(info, file);
get.download();
String newUrl = name;
//logger.info("downToLocal baseUrl:" + url + " newUrl:" + newUrl + " fileName:" + name + " filePath:" + filePath);
return newUrl;
}
catch (Exception e){
file.delete();
throw e;
}
}