
io.afu.utils.http.Downloader Maven / Gradle / Ivy
package io.afu.utils.http;
import io.afu.common.exception.BaseException;
import org.apache.http.HttpEntity;
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;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
public class Downloader {
/**
*
* @param url 下载路径
* @param savePath 保存路径
* @throws BaseException 错误抛出
*/
public static void d(String url,String savePath) throws BaseException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
File file = new File(savePath);
if (!file.getParentFile().exists()){
if (!file.getParentFile().mkdirs()){
System.out.println("创建文件夹失败");
throw new BaseException("创建文件夹失败",-1);
}
}
httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
HttpEntity entity = response.getEntity();
long len = entity.getContentLength();
InputStream inputStream = entity.getContent();
FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath));
int inByte;
while ((inByte = inputStream.read()) != -1){
fileOutputStream.write(inByte);
}
inputStream.close();
fileOutputStream.close();
}catch (Exception e){
throw new BaseException(e);
}
finally {
try {
response.close();
}catch (Exception e){
throw new BaseException(e);
}
}
}catch (Exception e){
throw new BaseException(e);
}
finally {
try {
httpClient.close();
}catch (Exception e){
throw new BaseException(e);
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy