当前位置: 代码迷 >> Web前端 >> HttpClient跟JDK的HttpURLConnection抓取网络图片以及图片的重命名
  详细解决方案

HttpClient跟JDK的HttpURLConnection抓取网络图片以及图片的重命名

热度:350   发布时间:2013-11-09 17:06:34.0
HttpClient和JDK的HttpURLConnection抓取网络图片以及图片的重命名
package com.app.io;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
/**
 * @说明 从网上抓取图片保存到到本地
 * @Version 1.0
 */
@SuppressWarnings("all")
public class Test2 {
	/**
	 * 测试
	 * @param args
	 */
	public static void main(String[] args) {
		 getImages();
		String path1 = "D:/test";
		File fromFile = new File(path1);// 源文件夹
		fileRename(fromFile, "Img");
	}
	/**
	 * 将抓取的图片重命名
	 * @param fileDir
	 * @param sequenceCode
	 */
	public static void fileRename(File fileDir, String sequenceCode) {
		File[] files = fileDir.listFiles();
		for (int k = 0; k < files.length; k++) {
			StringBuffer buffer = new StringBuffer(sequenceCode);
			if (files[k].isDirectory()) {
				fileRename(files[k], sequenceCode);
			} else {
				if (k < 10)
					buffer.append("_000").append(k).append(".png");
				else if (k >= 10 && k < 100)
					buffer.append("_00").append(k).append(".png");
				else if (k < 1000 && k >= 100)
					buffer.append("_0").append(k).append(".png");
				else
					buffer.append("_").append(k).append(".png");
				final int index = files[k].getName().lastIndexOf(".") + 1;
				final String fileType = files[k].getName().substring(index);
				buffer.append(".").append(fileType);
				final String name = buffer.toString();
				int lastIndex=name.lastIndexOf(".");//[Ljava.lang.String;@141d683找到最后的一个.将它重命名
				String ImgName=name.substring(0, lastIndex);
				final File dirFile = new File(fileDir, ImgName);
				System.out.println("Rename File Path:"+ files[k].getAbsolutePath());
				files[k].renameTo(dirFile);
			}
		}
	}
	/**
	 * 从网上抓取图片内容
	 * 对一张图片作抓取
	 * 如果有多张图片可以for
	 */
	private static void getImages(){
		String url="http://e.hiphotos.baidu.com/pic/w%3D310/sign=ef8237b59345d688a302b4a594c37dab/024f78f0f736afc3554ec1e3b219ebc4b64512f1.jpg";
			 
		byte[] btImg = getImageFromNetByUrl(url);
		if(null != btImg && btImg.length > 0){
			System.out.println("读取到:" + btImg.length + " 字节");
			String fileName = "";
			writeToDisk(btImg, fileName);
		}else{
			System.err.println("没有从该连接获得内容");
		}
	}
	/**
	 * 将图片写入到磁盘
	 * @param img 图片数据流
	 * @param fileName 文件保存时的名称	
	 */
	private static void writeToDisk(byte[] img, String ...fileName){
		try {
			File file = new File("d:/test/" + fileName);
			FileOutputStream fops = new FileOutputStream(file);
			fops.write(img);
			fops.flush();
			fops.close();
			System.out.println("图片已经写入到D盘");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 根据地址获得数据的字节流
	 * @param strUrl 网络连接地址
	 * @return
	 */
	private static byte[] getImageFromNetByUrl(String strUrl){
		try {
			InputStream inStream=null;
			/**
			 * 方法一
			 
			URL url = new URL(strUrl);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			
			inStream = conn.getInputStream();//通过输入流获取图片数据
			byte[] btImg = readStream(inStream);//得到图片的二进制数据
			return btImg;
			
			*/
			/**
			 * 
			 *方法二 HttpClient*/
			HttpClient client=new HttpClient();
			GetMethod method=new GetMethod(strUrl);//获取内容用GetMethod,经过测试PostMethod拿不到图片的内容
			int status=client.executeMethod(method);
			method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8"); //设置编码
			if(status==HttpStatus.SC_OK){
				inStream=method.getResponseBodyAsStream();
				byte[] btImg = readStream(inStream);//得到图片的二进制数据
				return btImg;
			}else{
				System.err.println("网络异常");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 从输入流中获取数据
	 * @param inStream 输入流
	 * @return
	 * @throws Exception
	 */
	private static byte[] readStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while( (len=inStream.read(buffer)) != -1 ){
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}
}

?

  相关解决方案