爬虫技术(2)--抓取网页java代码实现
2016-06-30 17:27
711 查看
package creeper.part1.capturepage; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; 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; //爬虫技术(1)--抓取网页 @SuppressWarnings("unused") public class capturePage { public static void main(String[] args) throws Exception { //声明一个HttpClient客户端,相当于打开一个浏览器(4.3以后都是CloseableHttpClient以前的已经过时) CloseableHttpClient httpClient=HttpClients.createDefault(); //创建代理,省略... try { //get方法,相当于打开了一个网页 String url="http://www.baidu.com"; HttpGet get=new HttpGet(url); System.out.println("---------URI----------"); System.out.println(get.getURI()); //创建响应处理器处理响应内容 ResponseHandler<String> handler=new ResponseHandler<String>(){ @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int status=response.getStatusLine().getStatusCode();//获取响应状态码 //对状态码进行判断处理 if(status>=200 && status<300 ){ HttpEntity entity=response.getEntity();//获取响应的数据 return entity==null?null:EntityUtils.toString(entity); }else{ throw new ClientProtocolException("status:"+status); } } }; //发送请求,相当于敲个回车 String responseBody=httpClient.execute(get, handler); System.out.println("----------------responseBody-----------------"); System.out.println(responseBody); System.out.println("----------------responseBody-----------------"); } catch (Exception e) { }finally{ httpClient.close(); } } }
相关文章推荐
- Hibernate注解使用以及Spring整合
- Java应用程序将对象分配到堆
- Eclipse的SVN提交过滤
- 关于java字节码框架ASM的学习
- Java成绩管理系统控制台版本
- JEECG 3.6.4 云插件开发版发布 ,企业级JAVA快速开发平台
- SpringMVC+Hibernate+Spring使用websevice报错
- ajax调用java,中文乱码解决办法
- Spring Security 和 Angular JS(2)
- myeclipse不编译的问题
- springmvc实现批量删除
- Spring MVC REST风格实现PUT、DELETE请求
- Java 读写文件的三种流介绍
- Java 线程池的使用详解
- 面向对象和面向过程
- 许多JVM选择在开始时首先解释Java字节码
- JAVA List<T> 如何初始化
- Spring JdbcTemplate详解
- 使用comm在java程序中管理本地端口
- java文件读取web-inf下的spring的xml配置文件