`
fantaxy025025
  • 浏览: 1250977 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类

利用Httpclient下载图片,java不用httpClient下载图片

 
阅读更多

=

=

=

from:https://blog.csdn.net/qq_41070393/article/details/106855795

/**
     * 下载图片
     */
    public static void downloadPicture(String url, String localPath) {
        //可关闭的httpclient客户端,相当于你打开一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        //构造httpget请求对象
        HttpGet httpGet = new HttpGet(url);
        //响应
        CloseableHttpResponse response = null;

        FileOutputStream fos = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            //获取响应结果  HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多实现
            HttpEntity entity = response.getEntity();

            // image/jpg  image/jpeg  image/png
            String contentType = entity.getContentType().getValue();//特别注意这里要getValue一下,否则这里不是string类型的数据而是reader类型的
            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";
            } else {
                OutTool.out("根据response头信息的contentType,图片的后缀没有找到合适的。默认使用jpeg。", url);
            }
            //字节流
            byte[] bytes = EntityUtils.toByteArray(entity);
            //String localpath = "D:\\LDS\\MavenDemoProject\\src\\main\\resources\\" + "我用httpclient的Get方式下载的图片" + suffix;
            String fileName = localPath + suffix;
            fos = new FileOutputStream(fileName);
            fos.write(bytes);

            //确保流关闭
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭输出流
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (closeableHttpClient != null) {
                try {
                    closeableHttpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

 

 

 

使用Httpclient下载图片

/**
     * 下载图片
     */
    public static void downloadPicture(String url, String localPath) {
        //可关闭的httpclient客户端,相当于你打开一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        //构造httpget请求对象
        HttpGet httpGet = new HttpGet(url);
        //响应
        CloseableHttpResponse response = null;

        FileOutputStream fos = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            //获取响应结果  HttpEntity不仅可以作为结果,也可以作为请求的参数实体,有很多实现
            HttpEntity entity = response.getEntity();

            // image/jpg  image/jpeg  image/png
            String contentType = entity.getContentType().getValue();//特别注意这里要getValue一下,否则这里不是string类型的数据而是reader类型的
            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";
            } else {
                OutTool.out("根据response头信息的contentType,图片的后缀没有找到合适的。默认使用jpeg。", url);
            }
            //字节流
            byte[] bytes = EntityUtils.toByteArray(entity);
            //String localpath = "D:\\LDS\\MavenDemoProject\\src\\main\\resources\\" + "我用httpclient的Get方式下载的图片" + suffix;
            String fileName = localPath + suffix;
            fos = new FileOutputStream(fileName);
            fos.write(bytes);

            //确保流关闭
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭输出流
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (closeableHttpClient != null) {
                try {
                    closeableHttpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

 

 

 

 

====文章1====

转载:https://www.iteye.com/blog/mybloglearn-818301
利用HttpClient下载图片
关键字: http
最近在项目中用到了HttpClient类库,有一个需求是下载网站中的图片,但是发现下载的图片不能打开,在网上搜索类似问题,没有找到解决的办法,无奈只得查看HttpClient的源代码,自己解决这个问题了。
在HttpMethodBase中发现如下代码:
java 代码

public String getResponseBodyAsString() throws IOException {  
        byte[] rawdata = null;  
        if (responseAvailable()) {  
            rawdata = getResponseBody();  
        }  
        if (rawdata != null) {  
            return EncodingUtil.getString(rawdata, getResponseCharSet());  
        } else {  
            return null;  
        }  
    }  
其中在返回网络资源的内容时,使用了指定的编码对网页内容或图片内容进行了编码,这样,对于图片来说内容当然不能显示了,所以在获得图片内容时要使用如下的方法:
java 代码

public byte[] getResponseBody() throws IOException   
或  
public InputStream getResponseBodyAsStream() throws IOException  
在把返回的内容存储到文件中,这样就实现了图片的自动下载,下面的代码演示了下载图片的过程

java 代码

import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
  
import org.apache.commons.httpclient.HttpClient;  
import org.apache.commons.httpclient.methods.GetMethod;  
  
/** 
* 用HttpClient下载图片 
* @author wei 
*/  
public class TestDownImage {  
      
    public static void main(String[] args) throws IOException{  
        HttpClient client = new HttpClient();  
        GetMethod get = new GetMethod("http://images.sohu.com/uiue/sohu_logo/beijing2008/2008sohu.gif");  
        client.executeMethod(get);  
        File storeFile = new File("c:/2008sohu.gif");  
        FileOutputStream output = new FileOutputStream(storeFile);  
        //得到网络资源的字节数组,并写入文件  
        output.write(get.getResponseBody());  
        output.close();  
    }  
}  

 

 

=

=

=

 

分享到:
评论

相关推荐

    JAVA利用HttpClient进行HTTPS接口调用

    JAVA利用HttpClient进行HTTPS接口调用

    (完整版)JAVA利用HttpClient进行POST请求(HTTPS).doc

    (完整版)JAVA利用HttpClient进行POST请求(HTTPS).doc

    java实现httpget和httppost请求httpclient-4.3.1.jar包

    利用httpclient-4.3.1.jar、httpcore-4.3.jar包,很简单的用java实现httpget和httppost请求。

    利用HttpClient和HtmlParser实现的简单爬虫(Java)

    利用HttpClient和HtmlParser实现的简单爬虫(Java)

    JAVA利用HttpClient进行HTTPS接口调用的方法

    本篇文章主要介绍了JAVA利用HttpClient进行HTTPS接口调用的方法,具有一定的参考价值,有兴趣的可以了解一下

    JAVA利用HttpClient进行POST请求(HTTPS)实例

    下面小编就为大家带来一篇JAVA利用HttpClient进行POST请求(HTTPS)实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起 小编过来看看吧

    httpClient调用wcf

    http_wcf调用 解决方案,用到了webService和 http_wcf调用 解决方案,用到了webService和http_wcf调用 解决方案,用到了webService和

    Java利用HttpClient模拟POST表单操作应用及注意事项

    本文主要介绍JAVA中利用HttpClient模拟POST表单操作,希望对大家有所帮助。

    HttpClient

    java.net包提供了基本的功能,它不通过HTTP访问资源...设计为可扩展,同时提供强大的支持HTTP协议的基础,HttpClient可提供给任何HTTP客户端应用程序,如Web浏览器,Web客户服务,或利用扩展HTTP协议的分布式通信系统。

    使用httpclient访问servlet

    java 使用httpclient访问servlet,方便两个不同服务器上的程序相互调用.

    httpclient4_中文版帮助文档.

    为扩展而设计,同时为基本的HTTP协议提供强大的支持,HttpClient组件也许就是构建HTTP客户端应用程序,比如web浏览器,web服务端,利用或扩展HTTP协议进行分布式通信的系统的开发人员的关注点。 1. HttpClient的范围...

    httpClient和htmlparse获取网页数据使用jar

    httpClient和htmlparse获取网页数据使用jar

    httpclient接口工具类

    利用httpclient封装了http的POST和GET请求方式,封装方法多样,返回结果为json

    HttpClient以及获取页面内容应用

    压缩包中含有多个文档,从了解httpclient到应用。 httpClient 1httpClint 1.1简介 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持...

    用HttpClient来模拟浏览器GET POST

    当然了,正如前面说到的,如果我们自己使用java.net.HttpURLConnection来搞定这些问题是很恐怖的事情,因此在开始之前我们先要介绍一下一个开放源码的项目,这个项目就是Apache开源组织中的httpclient,它隶属于...

    使用HttpClient 和 jsoup 下载 Google logo

    Google的logo,感觉设计的很好,最近看了java的jsoup(html 解析器)把Google的logo全部下载下来,另外,在Google logos页面发现都是英文的,通过利用Google翻译api对logo说明进行翻译,最终把图片信息以及翻译结果...

    JAVA上百实例源码以及开源项目

     util实现Java图片水印添加功能,有添加图片水印和文字水印,可以设置水印位置,透明度、设置对线段锯齿状边缘处理、水印图片的路径,水印一般格式是gif,png,这种图片可以设置透明度、水印旋转等,可以参考代码...

    JAVA获取邮件联系人

    方法2:利用httpclient模拟登录邮箱,抓取联系人页面的源代码---------使用http监听工具,抓出 邮箱登录、跳转(action)、联系人页面 等URL、form表单中隐藏的参数、高版本httpclient会自动管理cookie

    java 元搜索 调用百度 doc 文件示例

    利用元搜索下在百度 doc 文件。示例 利用httpclient 模拟像百度发请求

    java开源包10

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

Global site tag (gtag.js) - Google Analytics