25 HttpClient下载图片

httpClient对请求回来的response.getEntity()中的contentType和图片后缀进行比较判断

 这样就能下载我们想要的类型的图片了

    @Test
    public void testGetDownloadPicture() {
        /**
         *@param: []
         *@return: void
         *@description: 下载图片
         */
        String url_str = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic15.nipic.com%2F20110811%2F8029346_082444436000_2.jpg&refer=http%3A%2F%2Fpic15.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1636111937&t=c133a2ec6bef5ad21ce34161aebc3948";
        //可关闭的httpclient客户端,相当于你打开一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        //构造httpget请求对象
        HttpGet httpGet = new HttpGet(url_str);
        //响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            //获取响应结果  HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多实现
            HttpEntity entity = response.getEntity();

            // image/jpg  image/jpeg  image/png
            String contentType = entity.getContentType().getValue();//特别注意这里要getValue一下,否则这里不是string类型的数据而是eader类型的
            String suffix = ".jpeg";
            if (contentType.contains("jpeg") || contentType.contains("jpg")) {
                suffix = ".jpg";
            } else if (contentType.contains("bmp") || contentType.contains("bitmap")) {
                suffix = ".bmp";
            } else if (contentType.contains("png")) {
                suffix = "png";
            } else if (contentType.contains("gif")) {
                suffix = "gif";
            }
            //字节流
            byte[] bytes = EntityUtils.toByteArray(entity);
            String localpath = "D:\\LDS\\MavenDemoProject\\src\\main\\resources\\" + "我用httpclient的Get方式下载的图片" + suffix;
            FileOutputStream fos = new FileOutputStream(localpath);
            fos.write(bytes);
            //关闭输出流
            fos.close();
            //对HttpEntity操作的工具类:EntityUtils
            //String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8.name());
            //System.out.println(toStringResult);
            //确保流关闭
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                try {
                    closeableHttpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用 Apache HttpClient 进行文件下载的示例代码: ```java 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 org.apache.commons.io.IOUtils; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class HttpClientDownloadExample { public static void main(String[] args) { String fileUrl = "http://example.com/file.pdf"; String savePath = "/path/to/save/file.pdf"; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet(fileUrl); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); if (entity != null) { try (InputStream inputStream = entity.getContent(); OutputStream outputStream = new FileOutputStream(savePath)) { IOUtils.copy(inputStream, outputStream); } } } } catch (IOException e) { e.printStackTrace(); } } } ``` 请将 `fileUrl` 设置为要下载的文件的 URL,将 `savePath` 设置为要保存文件的本地路径。以上代码使用 `HttpClients.createDefault()` 创建了一个默认的 `CloseableHttpClient` 实例,并发送了一个 HTTP GET 请求来下载文件。然后,使用 `IOUtils.copy()` 方法将文件内容从输入流复制到输出流,完成文件的下载和保存。 请注意,这只是一个基本示例,并且没有包含错误处理或其他高级功能。在实际使用中,您可能需要添加更多的逻辑以处理各种情况和异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值