使用HttpClient下载网络图片

最近公司业务需求,需要去XX网站爬取数据,爬取速度过快时,会导致当前IP被封锁,让用户输入验证码。目前使用OCR识别图片验证码并提交,故需要下载验证码图片,研究了一下终于给实现了。在这里分享一下,希望对大家有用!


DownloadPictureTest类


package com.yulore.checkcode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * 下载图片工具类
 * 
 * @author bingbing feng 2013-03-14
 * 
 */
public class DownloadPictureTest {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		String uid = "871170f2-2598-48e5-9ee8-58ed6379d8931d2ec8";
		String s = "1363239309732";
		String fileName = "ex2.png";
		getCheckCodePicFromXX(uid,s,fileName);
	}

	private static void getCheckCodePicFromXX(String uid, String s,String fileName) {
		String url = "http://wap.xxx.com//p/ex.d?u_id="+uid+"&m=gvcd&s="+s;
		String dirPath = "D:/OCR_EX/";

		downloadPicture(url, dirPath, fileName);
	}

	/**
	 * 从网络上下载图片
	 */
	public static void downloadPicture(String url, String dirPath,
			String filePath) {
		
		DefaultHttpClient httpclient = new DefaultHttpClient();
		
		HttpGet httpget = new HttpGet(url);

		httpget
				.setHeader(
						"User-Agent",
						"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");
		httpget
				.setHeader("Accept",
						"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

		try {
			HttpResponse resp = httpclient.execute(httpget);
			if (HttpStatus.SC_OK == resp.getStatusLine().getStatusCode()) {
				HttpEntity entity = resp.getEntity();

				InputStream in = entity.getContent();

				savePicToDisk(in, dirPath, filePath);
				
				System.out.println("保存图片 "+filePath+" 成功....");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}

	/**
	 * 将图片写到 硬盘指定目录下
	 * @param in
	 * @param dirPath
	 * @param filePath
	 */
	private static void savePicToDisk(InputStream in, String dirPath,
			String filePath) {

		try {
			File dir = new File(dirPath);
			if (dir == null || !dir.exists()) {
				dir.mkdirs();
			}

			//文件真实路径
			String realPath = dirPath.concat(filePath);
			File file = new File(realPath);
			if (file == null || !file.exists()) {
				file.createNewFile();
			}

			FileOutputStream fos = new FileOutputStream(file);
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = in.read(buf)) != -1) {
				fos.write(buf, 0, len);
			}
			fos.flush();
			fos.close();

		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}


OK,搞定啦、、、



  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
HttpClient是一个开源的、用于发送HTTP请求的库。它被广泛应用于Java开发中,可以通过简单的代码实现对网络资源的访问。 HttpClient使用byte来处理字节数据。当我们需要发送或接收字节数据时,可以使用byte作为其数据类型。比如,当我们从网络下载图片或文件时,可以使用HttpClient发送HTTP请求获取字节流,并将字节流写入文件,或者将字节流转换为图片显示在界面上。 使用HttpClient发送HTTP请求获取字节流的步骤如下: 1. 创建HttpClient对象。 2. 创建HttpGet或HttpPost对象,并设置请求的URL地址和参数。 3. 执行请求,获取HttpResponse对象。 4. 从HttpResponse对象中获取HttpEntity对象。 5. 通过HttpEntity对象获取字节流。 6. 关闭HttpClient连接,释放资源。 字节流处理示例代码如下: ```java import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; 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.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientByteExample { public static void main(String[] args) { String url = "http://example.com/image.jpg"; // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpGet对象并设置URL HttpGet httpGet = new HttpGet(url); try { // 执行请求,获取HttpResponse对象 HttpResponse response = httpClient.execute(httpGet); // 获取HttpEntity对象 HttpEntity entity = response.getEntity(); // 获取字节流 InputStream in = entity.getContent(); // 将字节流写入文件 FileOutputStream out = new FileOutputStream("image.jpg"); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } // 关闭流 out.close(); in.close(); EntityUtils.consume(entity); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭HttpClient连接,释放资源 try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` 通过上述代码示例,我们可以使用HttpClient发送HTTP请求获取字节流,并将字节流写入文件。需要注意的是,在处理完字节流之后,我们需要手动关闭相关流和释放资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值