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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 【多目标优化】2. 非支配排序遗传算法 —(NSGA、NSGA-II)

    【多目标优化】2. 非支配排序遗传算法 —(NSGA、NSGA-II)多目标优化系列:MOP_1.多目标优化的相关基本概念MOP_2.非支配排序遗传算法—(NSGA、NSGA-II)MOP_3.基于分解的多目标进化算法—(MOEAD)1.非支配排序遗传算法(NSGA)1995年,Srinivas和Deb提出了非支配排序遗传算法(Non-dominatedSortingGeneticAlgorithms,NSGA)。这是一种基于P…

    2022年5月19日
    34
  • 分解质因数

    分解质因数分解质因数

    2022年4月24日
    55
  • Android语音采集两种方式MediaRecorder和AudioRecord

    Android语音采集两种方式MediaRecorder和AudioRecord

    2021年8月31日
    76
  • MySQL索引的优缺点

    MySQL索引的优缺点一、什么是索引索引用来快速地寻找那些具有特定值的记录,所有MySQL索引都以B-树的形式保存。如果没有索引,执行查询时MySQL必须从第一个记录开始扫描整个表的所有记录,直至找到符合要求的记录。表里面的记录数量越多,这个操作的代价就越高。如果作为搜索条件的列上已经创建了索引,MySQL无需扫描任何记录即可迅速得到目标记录所在的位置。例如有三张表分别是t1、t2、t3,每个表都有字段a1、a2、…

    2022年5月26日
    33
  • pest分析和swot分析的区别

    pest分析和swot分析的区别pest分析和swot分析的区别:pest分析是一种宏观环境分析,是通过分析企业所处的背景,从而判断企业所面临的状况。P是政治(Politics),E是经济(Economy),S是社会(Society),T是技术(Technology)。swot分析是建立在内外部环境分析之上所做的综合分析,得出相应的结论,从而确定公司战略选择的主要方向。S(strengths)是优势、W(weaknesses)是劣势,O(opportunities)是机会、T(threats)是威胁。想全面掌握pest

    2022年6月11日
    63
  • 语义分割的发展前景和概述[通俗易懂]

    语义分割的发展前景和概述[通俗易懂]感谢感谢!收藏用~原文出自:http://blog.geohey.com/ji-suan-ji-shi-jue-zhi-yu-yi-fen-ge/计算机视觉之语义分割2017年10月11日人工智能被认为是第四次工业革命,google,facebook等全球顶尖、最有影响力的技术公司都将目光转向AI,虽然免不了存在泡沫,被部分媒体夸大宣传,神经网络在图像识别,语音识别,自然语言处理,无人车等方面的贡…

    2022年8月21日
    6

发表回复

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

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