HttpClent4.3 的例子
package com.unbank.robotspider.util; import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List; import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.ContentEncodingHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger; public class CrawlerRequest { private final static Logger logger = Logger.getLogger(CrawlerRequest.class);
private static String constUserAgent_Chrome = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4"; public String getUrlRespHtml(String url) {
return getUrlRespHtml(url, null, null, 2000, "utf-8");
} /***
*
*
*
*/
public String getUrlRespHtml(String pageUrl,
List<NameValuePair> headerDict, List<NameValuePair> postDict,
int timeout, String htmlCharset) {
String respHtml = "";
String defaultCharset = "utf-8";
CloseableHttpResponse response = null;
HttpUriRequest request = null; CloseableHttpClient httpClient = HttpClients.createDefault();
URL url = null;
try {
url = new URL(pageUrl);
} catch (MalformedURLException e2) {
e2.printStackTrace();
}
URI uri = null;
try {
uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),
url.getQuery(), null);
} catch (URISyntaxException e2) {
e2.printStackTrace();
}// 防止pageUrl中出现空格
// httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
// CookiePolicy.BEST_MATCH);
// httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
// CookiePolicy.BEST_MATCH); // RequestConfig globalConfig = RequestConfig.custom()
// .setCookieSpec(CookieSpecs.BEST_MATCH)
// .build();
// CloseableHttpClient httpclient = HttpClients.custom()
// .setDefaultRequestConfig(globalConfig)
// .build();
// RequestConfig localConfig = RequestConfig.copy(globalConfig)
// .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
// .build();
// HttpGet httpGet = new HttpGet("/");
// httpGet.setConfig(localConfig); RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000).setConnectTimeout(5000)
.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();// 设置请求和传输超时时间 CookieStore cookieStore = new BasicCookieStore(); // logger.info(uri);
if (postDict != null) {
HttpPost postReq = new HttpPost(uri);
postReq.setConfig(requestConfig);
postReq.addHeader("User-Agent", constUserAgent_Chrome);
// postReq.addHeader(
// "Accept",
// "application/x-ms-application, image/jpeg, application/xaml+xml, "
// + "image/gif, image/pjpeg, application/x-ms-xbap, */*");
// postReq.addHeader("Accept-Language", "zh-CN");
// postReq.addHeader("", "zh-CN");
// postReq.addHeader("Connection", "close");
// postReq.addHeader("Content-Type", "text/html;charset=UTF-8");
try {
HttpEntity postBodyEnt = new UrlEncodedFormEntity(postDict,
"UTF-8");
postReq.setEntity(postBodyEnt);
} catch (Exception e) {
e.printStackTrace();
} request = postReq;
} else {
HttpGet getReq = new HttpGet(uri);
getReq.setConfig(requestConfig);
getReq.addHeader("User-Agent", constUserAgent_Chrome);
// getReq.addHeader(
// "Accept",
// "application/x-ms-application, image/jpeg, application/xaml+xml, "
// + "image/gif, image/pjpeg, application/x-ms-xbap, */*");
// getReq.addHeader("Accept-Language", "zh-CN");
// getReq.addHeader("", "zh-CN");
// getReq.addHeader("Connection", "close");
request = getReq; } HttpClientContext localContext = HttpClientContext.create();
localContext.setCookieStore(cookieStore);
try {
response = httpClient.execute(request, localContext);
} catch (Exception e) {
// logger.info(url + "=====读取出错===" + e);
for (int i = 0; i < 5; i++) {
if (response != null) {
break;
}
try {
Thread.sleep(((int) (Math.random() * 6) + 1) * 1000);
response = httpClient.execute(request, localContext);
} catch (Exception e1) {
// logger.info("读取失败次数" + i);
} } }
try {
if (response != null
&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity respEnt = response.getEntity();
// ContentType contentType = ContentType.getOrDefault(respEnt);
// text/html; charset=utf-8
// String charset = StringUtil.getStringByReg(
// contentType.toString(), "charset=([^;]*)");
// if (charset == null || charset.isEmpty()) {
//
// } else {
// htmlCharset = charset.split("=")[1];
// }
if ((null == htmlCharset) || htmlCharset.isEmpty()) {
htmlCharset = defaultCharset;
}
respHtml = EntityUtils.toString(respEnt, htmlCharset); } else {
// 保存到数据库
}
} catch (ClientProtocolException cpe) {
logger.info(url + "=====读取出错===" + cpe);
// cpe.printStackTrace();
} catch (IOException ioe) {
logger.info(url + "=====读取出错===" + ioe);
// ioe.printStackTrace();
} finally { try {
cookieStore.clear();
request.abort();
if (response != null) { response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
logger.info(e);
}
} return respHtml;
} }
HttpClent4.3 的例子的更多相关文章
- SQLServer地址搜索性能优化例子
这是一个很久以前的例子,现在在整理资料时无意发现,就拿出来再改写分享. 1.需求 1.1 基本需求: 根据输入的地址关键字,搜索出完整的地址路径,耗时要控制在几十毫秒内. 1.2 数据库地址表结构和数 ...
- C#+HtmlAgilityPack+XPath带你采集数据(以采集天气数据为例子)
第一次接触HtmlAgilityPack是在5年前,一些意外,让我从技术部门临时调到销售部门,负责建立一些流程和寻找潜在客户,最后在阿里巴巴找到了很多客户信息,非常全面,刚开始是手动复制到Excel, ...
- REGEX例子
作为REGEX的例子,代码9.3显示了一个给定的文件有多少行,具有给定的模式,通过命令行输入(注:有更有效率的方式来实现这个功能,如Unix下的grep命令,在这里只是给出了另一种方式).这个程序像下 ...
- CSharpGL(25)一个用raycast实现体渲染VolumeRender的例子
CSharpGL(25)一个用raycast实现体渲染VolumeRender的例子 本文涉及的VolumeRendering相关的C#代码是从(https://github.com/toolchai ...
- 简单例子了解View的事件分发
什么是事件分发 我们在写自定义ViewGroup或者自定义View的时候经常要处理用户的点击事件,如果我们的View在最底层,他在很多ViewGroup里面,我们如何让我们的点击事件准确传递到View ...
- 简单的例子了解自定义ViewGroup(一)
在Android中,控件可以分为ViewGroup控件与View控件.自定义View控件,我之前的文章已经说过.这次我们主要说一下自定义ViewGroup控件.ViewGroup是作为父控件可以包含多 ...
- kqueue例子
网络服务器通常都使用epoll进行异步IO处理,而开发者通常使用mac,为了方便开发,我把自己的handy库移植到了mac平台上.移植过程中,网上居然没有搜到kqueue的使用例子,让我惊讶不已.为了 ...
- 今天有群友不是很清楚htm直接存数据库的危害,我简单举个例子
通过这个案例就知道为什么不要把原生的html放数据库了 常见的几种转码 常用的几种显示方法 只有原生html和最下面一种弹框了,变成了持久xss 如果是Ajax的方式,请用@Ajax.JavaS ...
- ElasticSearch 5学习(5)——第一个例子(很实用)
想要知道ElasticSearch是如何使用的,最快的方式就是通过一个简单的例子,第一个例子将会包括基本概念如索引.搜索.和聚合等,需求是关于公司管理员工的一些业务. 员工文档索引 业务首先需要存储员 ...
随机推荐
- 点餐系统mealsystem.sql
/* Navicat MySQL Data Transfer Source Server : localhost Source Server Version : 50162 Source Host : ...
- Sprint 3计划
一.计划目标: 1.完成基本的首页面的信息查询功能 2.学生家教用户注册和登录,将信息存储到数据库 3.完成家教的资格评定设定和个人教学内容备份信息 二.燃尽图 三.项目具体工作细则 待明天工作会议分 ...
- struts.xml中出现Package struts2 extends undefined package struts-default解决办法
在struts.xml中出现extends undefined package struts-default,经过查阅资料原来是因为没有联网的缘故.这样解决:在myeclipse中关联本地的dtd文件 ...
- HNU 13308 Help cupid
Help cupid Problem's Link: http://acm.hnu.cn/online/?action=problem&type=show&id=13308&c ...
- C#如何使用异步编程
怎么使用异步,就是用委托进行处理,如果委托对象在调用列表中只有一个方法,它就可以异步执行这个方法.委托类有两个方法,叫做BeginInvoke和EndInvoke,它们是用来异步执行使用. 异步有三种 ...
- asp.net.mvc 中form表单提交控制器的2种方法和控制器接收页面提交数据的4种方法
MVC中表单form是怎样提交? 控制器Controller是怎样接收的? 1..cshtml 页面form提交 (1)普通方式的的提交
- 从零开始学习Linux(mkdir and rmdir)
今天说mkdir 和 rmdir.因为mkdir 内容比较少.而且也很好理解. 对于mkdir来说,一般只用到 -p -m,我只用过-p参数,-m也是刚刚看的. 先说不带参数的: mkdir tes ...
- [PHP] 读取大文件并显示
使用PHP读取日志文件,当文件比较大的时候,会报内存不足,因此应该部分读取,读取指定的行数的数据 PHP代码: <?php class Test{ //日志路径 const LOG_PATH=& ...
- MySQL 数据库 InnoDB 和 MyISAM 数据引擎的差别
InnoDB和MyISAM是在使用MySQL最常用的两个表类型,各有优缺点,视具体应用而定.基本的差别为:MyISAM类型不支持事务处理等高级处理,而InnoDB类型支持.MyISAM类型的表强调的是 ...
- SharpGL学习笔记(十四) 材质:十二个材质球
材质颜色 OpenGL用材料对光的红.绿.蓝三原色的反射率来近似定义材料的颜色.象光源一样,材料颜色也分成环境.漫反射和镜面反射成分,它们决定了材料对环境光.漫反射光和镜面反射光的反射程度.在进行光照 ...