HttpClient下载文件--并保存的方法及示例分享

乔欣 Java经验 发布时间:2023-03-15 22:17:32 阅读数:8334 1
下文笔者讲述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();
    }
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202303/16788899036055.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者