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是如何使用的,最快的方式就是通过一个简单的例子,第一个例子将会包括基本概念如索引.搜索.和聚合等,需求是关于公司管理员工的一些业务. 员工文档索引 业务首先需要存储员 ...
随机推荐
- 看看如何面试前端工程师:Github很重要
从程序员的角度提出要去学习哪些知识,下面这篇文章从面试官的角度介绍到面试时可能会问到的一些问题.不过我想先给你们一个忠告,招聘是一件非常艰巨的任务,在45分钟内指出一名侯选人是否合适是你需要完成的任务 ...
- Memcached入门
Memcached是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载. 它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提供动态.数据库驱动网站的速度. Memcache ...
- JavaScript执行顺序分析
之前从JavaScript引擎的解析机制来探索JavaScript的工作原理,下面我们以更形象的示例来说明JavaScript代码在页面中的执行顺序.如果说,JavaScript引擎的工作机制比较深奥 ...
- SQL 日期转换(阳历转阴历)
--步骤:创建日期表,放初始放初始化资料 --因为农历的日,是由天文学家推算出来,到现在只有到年,以后的有了还可以加入! if object_id('SolarData') is not nulldr ...
- VS如何显示行号
1.随便打开一个项目,可以看到代码框内并没有显示行号 2.选择“工具”-“选项”,打开后界面如下 3.选择文本编辑器,找到下图中的“行号”并勾选 4.行号可以显示了
- 个人信息管理PIM——密码管理工具软件
密码管理工具 以KeePass为主,结合LastPass在线浏览器网页密码.有钱银可以考虑1Password. KeePass LastPass 1Password 价格费用 免费开源 普通版:免费 ...
- VS 自定义新建文件模板方法
自定义新建文件模板方法 VS 2010 及VS2008 自定义模板的方法如下: 结合VS工具,其下的插件也层出不穷.今天重点给大家介绍如何使用VS2010自定义新建文件模版,新建文件时,添加个 ...
- IBatis 配置一对多
-------说明-------- IBatis 版本2.0 配置一对多 namespace = testDao ------------------ /** *班级的resultMap *Class ...
- KMA & ex_KMP---Revolving Digits
HDU 4333 Description One day Silence is interested in revolving the digits of a positive integer. I ...
- 亲们! 首次见面! 带来不适!多多见谅!--------->>Bank系统
亲们!您们好! 讲一下Bank系统的做法: 01.首先创建一个Card类 using System; using System.Collections.Generic; using System.Li ...