HttpClient_自定义cookie策略
实际使用client的过程中,会遇到一种情况,如cookie的Key为空的,此时默认的cookie的策略处理cookie是会报错。
这时咱可以通过重写cookiestore策略来解决如:
/**
* @description 自定义Cookie策略
*
* @title setCustomCookieSpec
* @param builder
* @return void
*/
private static void setCustomCookieSpec(HttpClientBuilder builder) { CookieSpecProvider easySpecProvider = new CookieSpecProvider() { public org.apache.http.cookie.CookieSpec create(HttpContext context) { return new BrowserCompatSpec() {
public void validate(Cookie cookie, CookieOrigin origin)
throws MalformedCookieException {
} protected List<Cookie> parse(final HeaderElement[] elems,
final CookieOrigin origin)
throws MalformedCookieException {
final List<Cookie> cookies = new ArrayList<Cookie>(
elems.length);
for (final HeaderElement headerelement : elems) {
final String name = headerelement.getName();
final String value = headerelement.getValue();
if (value == null) {
continue;
}
if (name == null || name.length() == 0) {
throw new MalformedCookieException(
"Cookie name may not be empty");
} final BasicClientCookie cookie = new BasicClientCookie(
name, value);
cookie.setPath(getDefaultPath(origin));
cookie.setDomain(getDefaultDomain(origin)); // cycle through the parameters
final NameValuePair[] attribs = headerelement
.getParameters();
for (int j = attribs.length - 1; j >= 0; j--) {
final NameValuePair attrib = attribs[j];
final String s = attrib.getName().toLowerCase(
Locale.ENGLISH); cookie.setAttribute(s, attrib.getValue()); final CookieAttributeHandler handler = findAttribHandler(s);
if (handler != null) {
handler.parse(cookie, attrib.getValue());
}
}
cookies.add(cookie);
}
return cookies;
} };
} };
Registry<CookieSpecProvider> r = RegistryBuilder
.<CookieSpecProvider> create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY,
new BrowserCompatSpecFactory())
.register("easy", easySpecProvider).build();
builder.setDefaultCookieSpecRegistry(r);
}
最后上个完整的代码:
package com.lkb.manager.httpclient; import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException; import org.apache.http.HeaderElement;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieAttributeHandler;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.BestMatchSpecFactory;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.impl.cookie.BrowserCompatSpecFactory;
import org.apache.http.protocol.HttpContext; import com.lkb.manager.util.LogUtil;
import com.lkb.manager.util.SpiderUtil; public class HttpClientUtil { /**
* @Fields CURRENT_HTTP_CLIENT_CONTEXT : httpclient 上下文
*/
private static final String HTTP_CLIENT_CONTEXT = "HttpClientUtil.HtppClientContext"; /**
* @Fields CURRENT_HTTP_CLIENT : httpclient
*/
public static final String HTTP_CLIENT = "HttpClientUtil.HttpClient"; public static CloseableHttpClient HttpClient(){
CloseableHttpClient client = (CloseableHttpClient)SpiderUtil.getSessions().get(HTTP_CLIENT);
if(client==null){
client = HttpClientUtil.getHttpClient();
SpiderUtil.getSessions().put(HTTP_CLIENT, client);
}
return client;
}
public static HttpClientContext HttpClientContext(){
HttpClientContext context = (HttpClientContext)SpiderUtil.getSessions().get(HTTP_CLIENT_CONTEXT);
if(context==null){
context = HttpClientContext.create();
SpiderUtil.getSessions().put(HTTP_CLIENT_CONTEXT, context);
}
return context;
} public static CloseableHttpClient getHttpClient(){
CloseableHttpClient client = null;
for (int i = 0; i < 2; i++) {
try{
HttpClientBuilder builder = createSSLClientDefault();
setCustomCookieSpec(builder);//cookie 策略
setExecutionCount(builder);
setKeepAliveDuration(builder);
client = builder.build();
}catch(Exception e){
e.printStackTrace();
}
if(client!=null){
return client;
}
}
LogUtil.error(null,"HttpClient初始化失败!");
return null;
} /**
* https通用策略
* @Title: createSSLClientDefault
* @return HttpClientBuilder 返回类型
* @throws
*/
private static HttpClientBuilder createSSLClientDefault(){
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
//信任所有
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf);
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return null;
} /**
* @description 自定义Cookie策略
*
* @title setCustomCookieSpec
* @param builder
* @return void
*/
private static void setCustomCookieSpec(HttpClientBuilder builder) { CookieSpecProvider easySpecProvider = new CookieSpecProvider() { public org.apache.http.cookie.CookieSpec create(HttpContext context) { return new BrowserCompatSpec() {
public void validate(Cookie cookie, CookieOrigin origin)
throws MalformedCookieException {
} protected List<Cookie> parse(final HeaderElement[] elems,
final CookieOrigin origin)
throws MalformedCookieException {
final List<Cookie> cookies = new ArrayList<Cookie>(
elems.length);
for (final HeaderElement headerelement : elems) {
final String name = headerelement.getName();
final String value = headerelement.getValue();
if (value == null) {
continue;
}
if (name == null || name.length() == 0) {
throw new MalformedCookieException(
"Cookie name may not be empty");
} final BasicClientCookie cookie = new BasicClientCookie(
name, value);
cookie.setPath(getDefaultPath(origin));
cookie.setDomain(getDefaultDomain(origin)); // cycle through the parameters
final NameValuePair[] attribs = headerelement
.getParameters();
for (int j = attribs.length - 1; j >= 0; j--) {
final NameValuePair attrib = attribs[j];
final String s = attrib.getName().toLowerCase(
Locale.ENGLISH); cookie.setAttribute(s, attrib.getValue()); final CookieAttributeHandler handler = findAttribHandler(s);
if (handler != null) {
handler.parse(cookie, attrib.getValue());
}
}
cookies.add(cookie);
}
return cookies;
} };
} };
Registry<CookieSpecProvider> r = RegistryBuilder
.<CookieSpecProvider> create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY,
new BrowserCompatSpecFactory())
.register("easy", easySpecProvider).build();
builder.setDefaultCookieSpecRegistry(r);
} /**
* 默认请求次数
* @param builder
*/
private static void setExecutionCount(HttpClientBuilder builder){
HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(
IOException exception,
int executionCount,
HttpContext context) {
if (executionCount >= 4) {
// 如果已经重试了5次,就放弃
return false;
}
if (exception instanceof InterruptedIOException) {
// 超时
return false;
}
if (exception instanceof UnknownHostException) {
// 目标服务器不可达
return false;
}
if (exception instanceof ConnectTimeoutException) {
// 连接被拒绝
return false;
}
if (exception instanceof SSLException) {
// ssl握手异常
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// 如果请求是幂等的,就再次尝试
return true;
}
return false;
} };
builder.setRetryHandler(myRetryHandler);
}
/**关闭连接*/
public static void colse(){
try {
CloseableHttpClient c = (CloseableHttpClient) SpiderUtil.getSessions().get(HttpClientUtil.HTTP_CLIENT);
if(c!=null){
c.close();
}
} catch (IOException e) {
LogUtil.error(e,"HttpClient关闭失败");
}
} private static void setKeepAliveDuration(HttpClientBuilder builder){
ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(
HttpResponse response,
HttpContext context) {
long keepAlive = super.getKeepAliveDuration(response, context);
if (keepAlive == -1) {
//如果服务器没有设置keep-alive这个参数,我们就把它设置成5秒
keepAlive = 4000;
}
return keepAlive;
} };
//定制我们自己的httpclient
builder.setKeepAliveStrategy(keepAliveStrat);
} }
HttpClient_自定义cookie策略的更多相关文章
- python之路-----django 自定义cookie签名
1.默认自定义cookie 在使用扩展签名时,会根据settings 配置中的 SIGNING_BACKEND 来运行加密方法,默认使用 django.core.signing.TimestampS ...
- python3使用requests模块完成get/post/代理/自定义header/自定义Cookie
一.背景说明 http请求的难易对一门语言来说是很重要的而且是越来越重要,但对于python一是urllib一些写法不太符合人的思维习惯文档也相当难看,二是在python2.x和python3.x中写 ...
- python3 get/post/使用代理/自定义header/自定义Cookie
说明:urllib发送http请求并不是很人性化,更推荐使用在urllib基础上封装的.python2和python3都兼容的requests模块,移步查看. 一.get请求 get请求就是在构造Re ...
- Spring Cloud Netflix Ribbon详细介绍及自定义规则策略
之前文章我们介绍了如何配置具有Ribbon轮询机制的负载均衡策略的消费者,这次来具体了解一下Ribbon的一些细节,以及如何自定义负载均衡策略等. 说一下Ribbon实现负载均衡的大致思路.它通过用@ ...
- 【Kafka】自定义分区策略
自定义分区策略 思路 Command+Option+shift+N 调出查询页面,找到producer包的Partitioner接口 Partitioner下有一个DefaultPartitioner ...
- 接口新建学习---cookie策略
一.为什么要添加cookie? 模拟浏览器,因为http是无状态协议,像览器一样的存储和发送Cookie,如果发送一个http请求他的响应中包含Cookie,那么Cookie Manager就会自动地 ...
- SpringBoot 自定义内容协商策略 configureContentNegotiation
在自定义的config配置类中,重写configureContentNegotiation方法 @Bean public WebMvcConfigurer webMvcConfigurer(){ re ...
- ES 09 - 定制Elasticsearch的分词器 (自定义分词策略)
目录 1 索引的分析 1.1 分析器的组成 1.2 倒排索引的核心原理-normalization 2 ES的默认分词器 3 修改分词器 4 定制分词器 4.1 向索引中添加自定义的分词器 4.2 测 ...
- 利用js里的Dom和Date,自定义cookie的前端设置方法
通过浏览器访问url时候浏览器会携带cookie,可利用cookie进行信息验证如用户验证,cookie前后端都可获取设置,后端用self.get_cookie和self.set_cookie,前端可 ...
随机推荐
- Python之路【第二十篇】Tornado框架
Tornado Tornado是使用Python编写的一个强大的.可扩展的Web服务器.它在处理严峻的网络流量时表现得足够强健,但却在创建和编写时有着足够的轻量级,并能够被用在大量的应用和工具中. 我 ...
- C++程序设计——知识点总结
C++程序设计课程的总结,方便以后快速查阅和复习 Week 2 从C走进C++ 函数指针 函数名是函数的入口地址,指向函数的指针称为"函数指针". 比如,qsort库函数: voi ...
- 深入理解javascript原型和闭包(18)——补充:上下文环境和作用域的关系
本系列用了大量的篇幅讲解了上下文环境和作用域,有些人反映这两个是一回儿事.本文就用一个小例子来说明一下,作用域和上下文环境绝对不是一回事儿. 再说明之前,咱们先用简单的语言来概括一下这两个的区别. 0 ...
- PhpStorm 集成 开源中国(oschina.net)的Git项目,提交SVN时注意事项
第一步:配置 git.exe File -> Default Settings -> Version Control -> Git -> Path go Git executa ...
- 【荐】说说CSS Hack 和向后兼容
人一旦习惯了某些东西就很难去改,以及各种各样的原因,新的浏览器越来越多,而老的总淘汰不了.增长总是快于消亡导致了浏览器兼容是成了谈不完的话题.说 到浏览器兼容,CSS HACK自然而然地被我们想起.今 ...
- Swift3.0P1 语法指南——类和结构体
原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...
- POJ2342 树形dp
原题:http://poj.org/problem?id=2342 树形dp入门题. 我们让dp[i][0]表示第i个人不去,dp[i][1]表示第i个人去 ,根据题意我们可以很容易的得到如下递推公式 ...
- ecshop中foreach的详细用法归纳
ec模版中foreach的常见用法. foreach 语法: 假如后台:$smarty->assign('test',$test); {foreach from=$test item=list ...
- espcms特殊标签
内页banner图从后台调用分类图片 <div style="background:url({%$rootdir%}{%find:type class=$type.topid out= ...
- Vim 键盘指令高清图
个人感觉挺好用的 推荐大家使用windows版的vim,个人用着感觉不错,在linux上用惯了vim的朋友可以试试这个.