HttpClient爬取网站及图片

1、什么是HttpClient?

HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

通过Java程序模拟浏览器访问网页,获取网页代码及图片的应用程序。

2、上代码:

在pom.xml中加入依赖关系:

<dependency>
	    <groupId>org.apache.httpcomponents</groupId>
	    <artifactId>httpclient</artifactId>
	    <version>4.5.2</version>
</dependency>

项目代码:

public static void main(String[] args) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpClient实例
		HttpGet httpGet = new HttpGet("http://www.tuicool.com"); // 创建Httpget实例
		//设置Http报文头信息
		httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0");
		CloseableHttpResponse response = null;
		response = httpClient.execute(httpGet); // 执行http get请求
		HttpEntity httpEntity = response.getEntity(); // 获取返回实体
		String web = EntityUtils.toString(httpEntity, "utf-8"); // 解析实体
		System.out.println("网页内容是:");
		System.out.println(web);
                //获取返回信息
String ContentType = httpEntity.getContentType().getValue();
System.out.println("Content-Type:"+ContentType);
System.out.println("Status:"+response.getStatusLine().getStatusCode());//获取返回码:200 404 500等
		response.close(); // 关闭response
		httpClient.close(); // 关闭HttpClient实体
	}


3、请求图片:

1)获取图片后,以InputStream的形式返回,可以通过new File 及 new OutputStream 的方法保存图片。

2)同时也可以通过Apache的工具包(本质上是封装第一种方法,底层实现原理相同)

需要在pom.xml中加入如下依赖关系:

<dependency>
	    <groupId>commons-io</groupId>
	    <artifactId>commons-io</artifactId>
	    <version>2.5</version>
</dependency>

 

项目代码:

public static void main(String[] args) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpClient实例
		HttpGet httpGet = new HttpGet("http://www.java1234.com/uploads/allimg/170610/1-1F610195021142.jpg"); // 创建Httpget实例
		//设置Http报文头信息
		httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0");
		CloseableHttpResponse response = null;
		response = httpClient.execute(httpGet); // 执行http get请求
		HttpEntity entity = response.getEntity(); // 获取返回实体
		if(null != entity){
			System.out.println("ContentType:"+entity.getContentType().getValue());
			InputStream inputStream = entity.getContent();//返回一个输入流
			//输出图片
			FileUtils.copyInputStreamToFile(inputStream, new File("D://a.jpg"));//引用org.apache.commons.io.FileUtils
		}
		response.close(); // 关闭response
		httpClient.close(); // 关闭HttpClient实体
}



原文地址:https://www.cnblogs.com/ryelqy/p/10104164.html