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是如何使用的,最快的方式就是通过一个简单的例子,第一个例子将会包括基本概念如索引.搜索.和聚合等,需求是关于公司管理员工的一些业务. 员工文档索引 业务首先需要存储员 ...
随机推荐
- phpBB论坛 代码 语法高亮 模块 Codebox Plus
phpBB代码语法高亮模块 Codebox Plus Code-By.Org (https://www.phpbb.com/customise/db/mod/codebox_plus/) (https ...
- LeetCode - 30. Substring with Concatenation of All Words
30. Substring with Concatenation of All Words Problem's Link --------------------------------------- ...
- P6 EPPM 16 R1 文档和帮助系统
P6 EPPM 16 R1 文档和帮助系统 https://docs.oracle.com/cd/E74894_01/ http://docs.oracle.com/cd/E68202_01/clie ...
- 【EF 译文系列】重试执行策略的局限性(EF 版本至少为 6)
原文链接:Limitations with Retrying Execution Strategies (EF6 onwards) 当使用重试执行策略的时候,大体有以下两种局限性: 不支持以流的方式进 ...
- 11条javascript知识
1.局部变量和全局变量 var操作符定义的变量将成为定义该变量作用域中的局部变量.这个局部变量会在函数退出后销毁.不同于其他语言,javaScript不存在块级作用域. 全局变量就是window对象的 ...
- sql:MySQL 6.7 表,视图,存储过程结构查询
#数据库MySQL 6.7 use sakila; #查询表名 show tables; # SELECT TABLE_NAME,TABLE_ROWS FROM INFORMATION_SCHEMA. ...
- mysql防止重复插入记录方法总结
mysql防止重复插入记录方法总结 防止mysql重复插入记录的方法有很多种,常用的是ignore,Replace,ON DUPLICATE KEY UPDATE,当然我们也可以在php中加以判断了. ...
- kFreeBSD当前可以做的和不能做的
可以进行FAMP FreeBSD.Apache/Nginx.Mysql/PostGreSQL.PHP/Perl/Python 虚拟化 最易用的VirtualBox 无法安装 Java OpenJDK及 ...
- 四、MyBatis主配置文件
//备注:该博客引自:http://limingnihao.iteye.com/blog/1060764 在定义sqlSessionFactory时需要指定MyBatis主配置文件: Xml代码 收藏 ...
- C#中的索引器原理
朋友们,还记得我们在C#语言开发中用到过索引器吗? 记得在获得DataGridView控件的某列值时:dgvlist.SelectedRows[0].Cells[0].Value; 记得在获得List ...