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是如何使用的,最快的方式就是通过一个简单的例子,第一个例子将会包括基本概念如索引.搜索.和聚合等,需求是关于公司管理员工的一些业务. 员工文档索引 业务首先需要存储员 ...
随机推荐
- 如何花样展示自己的摄影作品?CSS+JS+Html
注意:Windows平台推荐使用Edge.Chrome.FireFox,部分浏览器打不开 P.S.慢慢用鼠标在图片上拖拽会感觉更神奇 // 0.5 ? 1 : -1; }, ease: fun ...
- Javascript语法去控制Web控件的Enabled属性
Web控件当使用Enabled属性时,它生成html之后会变成了disabled了.我们为了能够在javascript去控制控件的禁用与启用,得从这个disabled入手.如:
- 转帖一篇sixxpack破解的文章!
星期天闲着没事玩游戏,玩游戏不能无外挂.于是百度了半天,找到了一个,看介绍貌似不错,就下载了下来.一看,竟然是用.net写的,下意识地Reflector了一下.发现竟是一个叫actmp的程序集.如图: ...
- sql server2008中sql server身份能登录,window身份登录不了
用sql server身份的sa登录成功进入,一切正常,用window身份登录不了,问题如下
- 重新想象 Windows 8 Store Apps (37) - 契约: Settings Contract
[源码下载] 重新想象 Windows 8 Store Apps (37) - 契约: Settings Contract 作者:webabcd 介绍重新想象 Windows 8 Store Apps ...
- C# ICSharpCode.SharpZipLib.dll文件压缩和解压功能类整理,上传文件或下载文件很常用
工作中我们很多时候需要进行对文件进行压缩,比较通用的压缩的dll就是ICSharpCode.SharpZipLib.dll,废话不多了,网上也有很多的资料,我将其最常用的两个函数整理了一下,提供了一个 ...
- 根据IP地址获取地址所在城市帮助类(IPHelper)
很多类库都是需要在长时间的编写过程中进行积累的,进入软件编程行业已经是第五个年头了,从2011年写下第一行代码到现在不知道已经写了多少行代码了,时间也过得挺快的.最近事情比较多,也很少写博客了,最近项 ...
- 用Perl编写Apache模块
前言 Apache被许多大流量网站所嫌弃,但很多企业级的场景则更为适用. Apache httpd 从 2.0 之后,已经不仅仅局限于一个 http 的服务器,更是一个完善而强大.灵活而健壮且容易扩展 ...
- U-boot的环境变量值得注意的有两个: bootcmd 和bootargs
本文转载至:http://www.cnblogs.com/cornflower/archive/2010/03/27/1698279.html U-boot的环境变量值得注意的有两个: bootcmd ...
- 划分树---Feed the dogs
POJ 2761 Description Wind loves pretty dogs very much, and she has n pet dogs. So Jiajia has to fee ...