import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
* 资源下载工具
*
* @author fanlychie
*/
public class HttpClientUtils {
private static Logger log = LoggerFactory.getLogger(HttpClientUtils.class);
* 下载资源文件
*
* @param url
* 资源文件地址
* @param storeFolder
* 下载的文件存放的目录
*/
public static void download(String url, String storeFolder) {
String filename = null;
if (StringUtils.isNotBlank(url)) {
filename = url.substring(url.lastIndexOf("/") + 1, url.length());
}
download(url, storeFolder, filename);
}
* 下载资源文件
*
* @param url
* 资源文件地址
* @param storeFolder
* 下载的文件存放的目录
* @param filename
* 下载的文件的名称
*/
public static void download(String url, String storeFolder, String filename) {
try {
if (StringUtils.isBlank(url)) {
throw new IllegalArgumentException("外部链接地址为空");
}
HttpClient httpClient = HttpClientBuilder.create().build();
HttpUriRequest request = RequestBuilder.get().setUri(url).build();
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
log.info("downloading {} ( {} KB )", url, response.getEntity().getContentLength() / 1024);
String fileTempName = filename + ".temp";
File file = new File(storeFolder, fileTempName);
downloadFile(response.getEntity().getContent(), new FileOutputStream(file));
file.renameTo(new File(storeFolder, filename));
}
} catch (Throwable e) {
log.error("下载外部资源失败!", e);
}
}
* 下载文件
*
* @param in
* 输入流
* @param out
* 输入流
* @throws Throwable
*/
private static void downloadFile(InputStream in, OutputStream out) throws Throwable {
byte bytes[] = new byte[1024 * 1024 / 4];
int read;
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.close();
}
}