httpclient4下载图片 java实现[通俗易懂]

httpclient4下载图片 java实现[通俗易懂]有时候需要从网上抓取一下图片jpg、png等,也可以抓取zip等,这样就需要写程序才能达到想要的效果,下面是用httpclient4做一个工具类,非常的好用packagecom.wamei.tool;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.FileOutputStream;

大家好,又见面了,我是你们的朋友全栈君。

有时候需要从网上抓取一下图片jpg、png等,也可以抓取zip等,这样就需要写程序才能达到想要的效果,

下面是用httpclient4做一个工具类,非常的好用

package com.wamei.tool;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.UUID;

import com.wamei.util.ImageUtil;
import com.wamei.util.JsonResponseHelper;
import com.wamei.util.SystemConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by qixuan.chen on 2016/8/18.
 */
public class ImageDownloadUtil {

    private static final Logger logger = Logger.getLogger(ImageDownloadUtil.class);

    public static String download(HttpServletRequest request,String url, String savePath, Integer width, Integer height) {
        HttpClient httpclient = new DefaultHttpClient();
        String picSrc = "";
        String picType = url.substring(url.lastIndexOf(".")+1,url.length());
        String fileName = UUID.randomUUID().toString().replace("-", "")+"."+picType;
        String path = request.getSession().getServletContext().getRealPath(savePath+fileName);
        File storeFile = null;
        try {
            HttpGet httpget = new HttpGet(url);

            //伪装成google的爬虫
            httpget.setHeader("User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
            // Execute HTTP request
            logger.info("executing request: " + httpget.getURI());
            HttpResponse response = httpclient.execute(httpget);
            storeFile = new File(path);
            FileOutputStream output = new FileOutputStream(storeFile);

            // 得到网络资源的字节数组,并写入文件
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    byte b[] = new byte[1024];
                    int j = 0;
                    while( (j = instream.read(b))!=-1){
                        output.write(b,0,j);
                    }
                    output.flush();
                    output.close();
                } catch (IOException ex) {
                    // In case of an IOException the connection will be released
                    // back to the connection manager automatically
                    throw ex;
                } catch (RuntimeException ex) {
                    // In case of an unexpected exception you may want to abort
                    // the HTTP request in order to shut down the underlying
                    // connection immediately.
                    httpget.abort();
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    try { instream.close(); } catch (Exception ignore) {}
                }
                if (storeFile.exists()) {
                    BufferedImage newImage = ImageUtil.getFileImage(storeFile, width, height);
                    ImageIO.write(newImage, picType, storeFile);
                    picSrc = "http://"+ JsonResponseHelper.serverAddress+"/wamei/"+savePath+fileName;
                }

            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }


        return picSrc;

    }

    public static void main(String[] args) throws MalformedURLException {
        //抓取下面图片的测试
        //ImageDownloadUtil.download("http://blog.goyiyo.com/wp-content/uploads/2012/12/6E0E8516-E1DC-4D1D-8B38-56BDE1C6F944.jpg", "d:/aaa.jpg");
    }
}

参考代码:

package com.yododo.fds.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

public class JpgDownloadUtil {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(JpgDownloadUtil.class);

public static void download(String url, String filePathName) {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet(url);

//伪装成google的爬虫JAVA问题查询
httpget.setHeader("User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
// Execute HTTP request
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);

File storeFile = new File(filePathName);
FileOutputStream output = new FileOutputStream(storeFile);

// 得到网络资源的字节数组,并写入文件
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
byte b[] = new byte[1024];
int j = 0;
while( (j = instream.read(b))!=-1){
output.write(b,0,j);
}
output.flush();
output.close();
} catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;
} catch (RuntimeException ex) {
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection immediately.
httpget.abort();
throw ex;
} finally {
// Closing the input stream will trigger connection release
try { instream.close(); } catch (Exception ignore) {}
}
}

} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
httpclient.getConnectionManager().shutdown();
}
}

public static void main(String[] args) throws MalformedURLException {

//抓取下面图片的测试
JpgDownloadUtil.download("http://blog.goyiyo.com/wp-content/uploads/2012/12/6E0E8516-E1DC-4D1D-8B38-56BDE1C6F944.jpg", "c:/aaa.jpg");
}
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/163282.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • idea 2021.5.3过期后怎么输激活码[在线序列号]

    idea 2021.5.3过期后怎么输激活码[在线序列号],https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月20日
  • 网页性能优化之图片懒加载

    一、前言最近因为需要做一个小网站,但是呢,因为图片比较多,打开网页速度很慢,服务器压力就会很大。不仅影响渲染速度还会浪费带宽,比如一个1M大小的图片,并发情况下,达到1000并发,即同时有1000个人访问,就会产生1个G的带宽。于是就想到了图片懒加载来减轻服务器的压力,优先加载可视区域的内容,其他部分等进入了可视区域再加载,从而提高性能,可以大幅度的提高网页加载速度,效果很明显,于是想着将这个方…

    2022年4月8日
  • 淘宝刷流量软软件,互刷点击量,直通车点击系统【胖虎图图-互点专家】

    淘宝刷流量软软件,互刷点击量,直通车点击系统【胖虎图图-互点专家】软件绿色免安装,打开即可使用。软件大小:1.4MB支持平台:win2000/win2003/winxp/win7/win8下载地址:http://www.phtoto.com/download/胖虎图图-互动点击.rar【2013-8-12】更新日志:修复无法停止任务的bug; 【2013-8-11】更新日志:新增支持谷歌搜索;新增支持360搜索;新增支持搜

    2022年9月27日
  • 如何用格式工厂转换视频格式为mp4_格式工厂怎么转换avi

    如何用格式工厂转换视频格式为mp4_格式工厂怎么转换avi第一步:选择输出格式MP4。【▲图1】第二步:打开源视频文件。【▲图2】第三步:打开输出配置,选择视频编码:AVC(H264)。【▲图3】第四步:点击开始。【▲图4】第五步:找到输出视频。【▲图5】…

    2022年10月10日
  • codeblocks中文编码问题

    codeblocks中文编码问题其实这是老调重弹的问题了,在windows下面出现中文乱码大多都是编码格式的问题不一致的问题,最简单的就是uft-8和gbk冲突的问题。如果一个文件本来是以utf-8存的,但是以gbk打开,当然会出现乱码了。方法一:用utf-8打开文件linux中中文常用的格式是utf-8,minGW是gcc的编译器,默认是utf-8格式,但是我们打开Setting/Editor/EncodingSetting

    2022年7月26日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号