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

 

posted @ 2017-09-12 22:59  小葱拌豆腐~  阅读(1216)  评论(0编辑  收藏  举报