HttpClient 通过资源URL下载资源
使用富文本编辑器写文章什么的,从第三方拷贝过来的图文,里面的资源内容都是第三方的,如果第三方删除该资源,导致该文章也无法访问,故需要把文章中的第三方资源通过http下载到本地服务器,永久保存。
用到了以下三种方法:
1、纯IO写文件
/**
* 根据url下载文件,保存到filepath中
* @param url
* @param filepath
* @return
*/
public static void download(String url, String filepath) {
try {
HttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
//设置请求
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
*
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
*
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000).setConnectionRequestTimeout(1000)
.setSocketTimeout(3000).build();
httpGet.setConfig(requestConfig);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
File file = new File("C:\\Users\\XXX\\Downloads\\io");
FileOutputStream fileout = new FileOutputStream(file);
/**
* 根据实际运行效果 设置缓冲区大小
*/
byte[] buffer = new byte[cache];
int ch = 0;
while ((ch = is.read(buffer)) != -1) {
fileout.write(buffer, 0, ch);
}
is.close();
fileout.flush();
fileout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
注:由于该资源是网页使用,此处没有考虑文件类型,无文件格式后缀的文件,浏览器已然可以正常解析
2、使用HttpEntity自带工具
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
/**
* 使用httpClient自带的工具类
* @param url
*/
public static void downloadByWriteTo(String url){
try {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setConnectionRequestTimeout(1000)
.setSocketTimeout(3000).build();
CloseableHttpClient client = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig).build();
CloseableHttpResponse response = client.execute(new HttpGet(new URL(url).toURI()));
HttpEntity entity = response.getEntity();
File file = new File("C:\\Users\\XXX\\Downloads\\WriteTo");
entity.writeTo(new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}
3、使用nio工具类拷贝
public static void downloadByFilesCopy(String url){
try {
HttpClient client = HttpClients.createDefault();
HttpResponse response = client.execute(new HttpGet(url));
HttpEntity entity = response.getEntity();
File file = new File("C:\\Users\\XXX\\Downloads\\FilesCopy");
Files.copy(entity.getContent(),file.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
e.printStackTrace();
}
}
以上操作均需要导入HttpClient 包
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
本文介绍通过HttpClient使用三种不同方法从远程URL下载资源到本地服务器的详细步骤,包括纯IO写文件、使用HttpEntity自带工具及nio工具类拷贝。
2226

被折叠的 条评论
为什么被折叠?



