HttpClient下载文件--并保存的方法及示例分享
下文笔者讲述HttpClient下载文件及保存的方法分享,如下所示
实现思路:
1.引入HttpClient依赖
2.构造HttpClient对象
3.获取HttpClient对应的文件流
4.将获取的流信息保存到本地
即可达到下载文件并保存的目的
例:HttpClient下载文件并保存的示例分享
//引入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
/*
* urlPath:服务器文件路径
* filePath:文件生成路径
*/
public static void httpUrl(String urlPath,String filePath) throws IOException {
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(urlPath);
CloseableHttpResponse response = httpClient.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
// 得到实体
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
byte[] getData = readInputStream(inputStream);
File file = new File(filePath);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


