HttpClient(三)-- 抓取图片

使用HttpClient抓取图片,先通过 entity.getContent() 获取输入流,然后 使用 common io 中的文件复制 方法 将图片专区到本地,代码如下:

1.需要依赖common io包

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.5</version>
    </dependency>

2.Java代码:

public static void main(String[] args) throws ClientProtocolException, IOException {
        // 图片路径
        String url = "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1505227453&di=197253946d222b27d4894f18cfd00fe0&src=http://www2.chinaedu.com/101resource003/kewaiuser/dersk/yddd15/img/yddd15_1_clip_image001.jpg";
        // 创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httpGet实例
        HttpGet httpGet = new HttpGet(url);
        // 设置请求头消息
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 获取 .后缀
        String fileName = url.substring(url.lastIndexOf("."), url.length());
        
        if(response != null){
            HttpEntity entity = response.getEntity();  // 获取返回实体
            if(entity != null){
                System.out.println("Content-Type:" + entity.getContentType().getValue());
                InputStream inputStream =  entity.getContent();
                // 文件复制,common io 包下,需要 引入依赖
                FileUtils.copyToFile(inputStream, new File("C:joe" + fileName));
            }
        }
        if(response != null){
            response.close();
        }
        if(httpClient != null){
            httpClient.close();
        }
    }

3、HttpClient学习地址

  开源博客系统-HttpClient

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值