COOKIE保持回话

httpclient4.x自带维护回话的功能,只要使用同一个httpclient且未关闭连接,就可以使用相同的回话来访问其他要求登陆验证的服务。
如果需要使用HttpClient池,并且想要做到一次登陆的会话供多个httpClient连接使用,就需要自己保存回话信息。
客户端的回话信息是保存在cookie中的(JESSIONID),所以只需要将登陆成功返回的cookie复制到各个HttpClient使用即可。
使用Cookie的方法有两种,可以自己使用CookieStore来保存,也可以通过HttpClientContext上下文来维持

使用cookie的两种方法

*) 使用CookieStore来保存
*) 通过HttpClientContext上下文来维持

使用cookie测试登陆

public void testLogin(){
//间接创建HttpClient
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
ColseableHttpClient client = httpClientBuilder.build();
//直接创建client
CloseableHttpClient client = HttpClients.createDefault();
//--------------------------------------------------------------------------------
HttpPost httpPost = new HttpPost(loginUrl);
Map parameterMap = new HashMap();
paramterMap.put("username","admin");
paramterMap.put("password","admin123");
--------------------------------------------------------------------------------
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(getParam(paramterMap),"utf-8");
httpPost.setEntity(postEntity);
try{
//--执行post请求
HttpResponse httpResponse = client.execute(httpPost);
String location = httpResponse.getFirstHeader("Location").getValue();
printResponse(httpResponse);
//--执行get请求
HttpGet httpGet = new HttpGet(testUrl);
HttpResponse response1 = client.execute(httpGet);
printResponse(httpResponse);
--------------------------------------------------------------------------------
//cookie Store
setCookieStore(httpResponse);
//context 注意顺序
setContext();
}catch(Exception e){
e.printStackTrace();
}
}
--------------------------------------------------------------------------------
public static List<NameValuePair> getParam(Map parameterMap) {
List<NameValuePair> param = new ArrayList<NameValuePair>();
Iterator it = parameterMap.entrySet().iterator();
while (it.hasNext()) {
Entry parmEntry = (Entry) it.next();
param.add(new BasicNameValuePair((String) parmEntry.getKey(),
(String) parmEntry.getValue()));
}
return param;
}
-------------------------------------------------------------------------
public static void printResponse(HttpResponse httpResponse)
throws ParseException, IOException {
// 获取响应消息实体
HttpEntity entity = httpResponse.getEntity();
// 响应状态
System.out.println("status:" + httpResponse.getStatusLine());
System.out.println("headers:");
HeaderIterator iterator = httpResponse.headerIterator();
while (iterator.hasNext()) {
System.out.println("\t" + iterator.next());
}
// 判断响应实体是否为空
if (entity != null) {
String responseString = EntityUtils.toString(entity);
System.out.println("response length:" + responseString.length());
System.out.println("response content:"
+ responseString.replace("\r\n", ""));
}
}

通过CookieStore保持上下文的回话

static CookieStore cookieStore = null;

public void testCookieStore() throws Exception{
//使用cookieStore方式
cookieStore= setCookieStore();
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
HttpGet httpGet = new HttpGet(testUrl);
//执行get请求
try{
HttpResponse response = client.execute(httpGet);
printResponse(response);
}catch(Exception e){
e.printStackTrace();
}
} public static void setCookieStore(HttpResponse response){
cookieStore = new BasicCookieStore();
//JSSIONID
String setCookie - httpResponse.getFirestHeader("Set-Cookie").getValue();
String JESSIONID = setCookie.substring("JESSIONID=".length(),setCookie.indexOf(";"));
//新建一个COOKIE
BasicClientCookie cookie = new BasicClientCookie("JESSIONID",JESSIONID);
cookie.setVersion(0);
cookie.setDomain("127.0.0.1");
cookie.setPath("/path");
// cookie.setAttribute(ClientCookie.VERSION_ATTR, "0");
// cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "127.0.0.1");
// cookie.setAttribute(ClientCookie.PORT_ATTR, "8080");
// cookie.setAttribute(ClientCookie.PATH_ATTR, "/CwlProWeb");
cookieStore.addCookie(cookie);
}

使用context上下文保持回话

static HttpClientContext context = null;
public void testContext() throws Exception(
//使用context方式
CloseableHttpClient client = HttpClients.createDefault():
HttpGet httpGet = new HttpGet(testUrl);
try{
//执行get请求
HttpResponse httpResponse = client.execute(httpGet,context);
printResponse(httpResponse);
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭流并释放资源
client.close();
}
) public static void setContext() {
context = HttpClientContext.create();
Registry<CookieSpecProvider> registry = RegistryBuilder
.<CookieSpecProvider> create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()).build();
context.setCookieSpecRegistry(registry);
context.setCookieStore(cookieStore);
}

httpclient cookie保持会话的更多相关文章

  1. Java Web之会话管理一: 使用Cookie进行会话管理

    一.Cookie的概念 Cookie(会话)可以简单的理解为:用户开一个浏览器,点击多个链接,访问服务器多个web资源,然后关闭浏览器,整个过程称为一个会话. 二.会话过程中解决的问题 用户在使用浏览 ...

  2. HttpClient接口测试之会话保持

    HttpClient接口测试之会话保持     HttpClient4.X自带会话保持功能,使用同一个HttpClient未关闭的连接即可保持登陆会话,如果多个HttpClient想要使用一个登陆会话 ...

  3. express-12 Cookie与会话

    简介 HTTP是无状态协议.当浏览器中加载页面,然后转到同一网站的另一页面时,服务器和浏览器都没有任何内在的方法可以认识到,这是同一浏览器访问同一网站.换一种说法,Web工作的方式就是在每个HTTP请 ...

  4. 浏览器禁用Cookie,基于Cookie的会话跟踪机制失效的解决的方法

    当浏览器禁用Cookies时.基于Cookie的会话跟踪机制就会失效.解决的方法是利用URL重写机制跟踪用户会话. 在使用URL重写机制的时候须要注意.为了保证会话跟踪的正确性,全部的链接和重定向语句 ...

  5. 如何利用服务器下发的Cookie实现基于此Cookie的会话保持

    Cookie是一种在客户端保持HTTP状态信息的常用技术,基于Cookie的会话保持常常出现在很多AX的部署案例中,尤其是涉及电子交易的系统部署中.此类系统往往要求负载均衡设备按照服务器下发的Cook ...

  6. nginx第三方模块---nginx-sticky-module的使用(基于cookie的会话保持)

    目前的项目网站架构中使用了F5和nginx,F5用来做负载均衡,nginx只用作反向代理服务器.最近应客户的要求准备去掉F5,使用软负载.大家都知道nginx抗并发能力强,又可以做负载均衡,而且使用n ...

  7. 基于hi-nginx的web开发(python篇)——cookie和会话管理

    hi-nginx通过redis管理会话. 要开启管理,需要做三件事. 第一件开启userid: userid on; userid_name SESSIONID; userid_domain loca ...

  8. Cookie&Seesion会话 共享数据 工作流程 持久化 Servlet三个作用域 会话机制

    Day37 Cookie&Seesion会话 1.1.1 什么是cookie 当用户通过浏览器访问Web服务器时,服务器会给客户端发送一些信息,这些信息都保存在Cookie中.这样,当该浏览器 ...

  9. 使用Cookie进行会话管理

    javaweb学习总结(十一)——使用Cookie进行会话管理 一.会话的概念 会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话. ...

随机推荐

  1. 用Win32 实现进度条

    转载:http://www.cctry.com/thread-238862-1-1.html #include <windows.h> #include <commctrl.h> ...

  2. Python3基础 hasattr 测试类是否有指定的类属性

             Python : 3.7.0          OS : Ubuntu 18.04.1 LTS         IDE : PyCharm 2018.2.4       Conda ...

  3. Django框架(三) 复习总结与路由控制

    知识点回顾 MTV模型 model:模型,和数据库相关的 template:模板,存放html文件,模板语法(目的是将变量如何巧妙的嵌入到HTML页面中). views:视图函数 另加urls:url ...

  4. gulp报错插件gulp-notify 配置项

    var notify = require("gulp-notify"); module.exports = function(){ var args = Array.prototy ...

  5. Facebook广告API系列 3 Ads Management

    Facebook广告API系列 3 Facebook marketing API有三大组成部分: Audience Management Ads Management Ads Insights 本篇介 ...

  6. C# 如何调用启动窗体

    Program.cs中代码如下: using System; using System.Collections.Generic; using System.Windows.Forms; namespa ...

  7. 51nod 1102 面积最大的矩形(单调栈)

    http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1102 题意: 思路: 做法就是求出每个长方形向左向右所能延伸的最大距离. ...

  8. LA 3213 古老的密码

    https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&category=15& ...

  9. linux——压缩解压命令学习简单笔记

    一: 命令名称:gzip 命令英文原意:GNU zip 命令所在路径:/bin/gzip 执行权限:所有用户 语法:gzip 选项 [文件] 功能描述:压缩文件 压缩后文件格式:.gz 1:只能压缩文 ...

  10. ubuntu 14.04(desktop amd 64) nginx 安装启动停止

    sudo apt-get install nginx 关闭: sudo service nginx stop 启动: sudo nginx