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是如何使用的,最快的方式就是通过一个简单的例子,第一个例子将会包括基本概念如索引.搜索.和聚合等,需求是关于公司管理员工的一些业务. 员工文档索引 业务首先需要存储员 ...
随机推荐
- 循序渐进开发WinForm项目(3)--Winform界面层的项目设计
随笔背景:在很多时候,很多入门不久的朋友都会问我:我是从其他语言转到C#开发的,有没有一些基础性的资料给我们学习学习呢,你的框架感觉一下太大了,希望有个循序渐进的教程或者视频来学习就好了. 其实也许我 ...
- [CLR via C#]8. 方法
一.实例构造器和类(引用类型) 类实例构造器是允许将类型的实例初始化为良好状态的一种特殊的方法. 类实例构造器方法在"方法定义元数据表"中始终叫.ctor(代表constructo ...
- 当kfreebsd 用户遇见openSUSE系统
openSuse的系统工具集覆盖了四大主流桌面环境,是针对每一种桌面环境定制的独立的桌面体验.
- 常用 Git 命令清单(摘录)
来源:阮一峰的网络日志 网址:http://www.ruanyifeng.com/blog/2015/12/git-cheat-sheet.html 我每天使用 Git ,但是很多命令记不住. 一般来 ...
- ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var mysql 启动不了
ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var mysql 启动不了 ps -A | gr ...
- ASP.NET Web API 通过Authentication特性来实现身份认证
using System; using System.Collections.Generic; using System.Net.Http.Headers; using System.Security ...
- java微信开发(wechat4j)——支持微信JS-SDK的jsapi_ticket中控服务器
jsapi_ticket是使用js-sdk必须要的一个凭证,需要配置在js中. jsapi_ticket获取 要获取jsapi_ticket可以使用如下的方法 String jsapi_ticket ...
- linux 查看占用内存/CPU最多的进程
可以使用一下命令查使用内存最多的5个进程 ps -aux | sort -k4nr | head -n 5 或者 top (然后按下M,注意大写) 可以使用一下命令查使用CPU最多的5个进程 ps - ...
- Echarts图表控件使用总结1(Line,Bar)
问题篇(详解):http://www.cnblogs.com/hanyinglong/p/4708337.html 1.前言 a.在系统开发过程中可能会使用到图表控件,一个好的图标控件可以使我们的网站 ...
- [Angularjs]视图和路由(四)
写在前面 关于angularjs的路由的概念基本上这篇就要结束了,通过学习,以及在实际项目中的实践,还是比较容易上手的.自己也通过angularjs做了一个在app上的一个模块,效果还是可以的. 系列 ...