HttpClient4.x可以自带维持会话功能,只要使用同一个HttpClient且未关闭连接,则可以使用相同会话来访问其他要求登录验证的服务(见TestLogin()方法中的“执行get请求”部分)。
如果需要使用HttpClient池,并且想要做到一次登录的会话供多个HttpClient连接使用,就需要自己保存会话信息。因为客户端的会话信息是保存在cookie中的(JSESSIONID),所以只需要将登录成功返回的cookie复制到各个HttpClient使用即可。
使用Cookie的方法有两种,可以自己使用CookieStore来保存(见TestCookieStore()方法),也可以通过HttpClientContext上下文来维持(见TestContext()方法)。
附带HttpClient4.3示例代码 http://www.myexception.cn/program/1459749.html 。 package com.sunbin.httpSession; import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
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.BrowserCompatSpecFactory;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test; public class TestHttpClient { // 创建CookieStore实例
static CookieStore cookieStore = null;
static HttpClientContext context = null;
String loginUrl = "http://127.0.0.1:8080/CwlProClient/j_spring_security_check";
String testUrl = "http://127.0.0.1:8080/CwlProClient/account/querySubAccount.action";
String loginErrorUrl = "http://127.0.0.1:8080/CwlProClient/login/login.jsp"; @Test
public void testLogin() throws Exception {
System.out.println("----testLogin"); // // 创建HttpClientBuilder
// HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// // HttpClient
// CloseableHttpClient client = httpClientBuilder.build();
// 直接创建client
CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(loginUrl);
Map parameterMap = new HashMap();
parameterMap.put("j_username", "sunb012");
parameterMap.put("j_password", "sunb012");
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(
getParam(parameterMap), "UTF-8");
httpPost.setEntity(postEntity);
System.out.println("request line:" + httpPost.getRequestLine());
try {
// 执行post请求
HttpResponse httpResponse = client.execute(httpPost);
String location = httpResponse.getFirstHeader("Location")
.getValue();
if (location != null && location.startsWith(loginErrorUrl)) {
System.out.println("----loginError");
}
printResponse(httpResponse); // 执行get请求
System.out.println("----the same client");
HttpGet httpGet = new HttpGet(testUrl);
System.out.println("request line:" + httpGet.getRequestLine());
HttpResponse httpResponse1 = client.execute(httpGet);
printResponse(httpResponse1); // cookie store
setCookieStore(httpResponse);
// context
setContext();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} @Test
public void testContext() throws Exception {
System.out.println("----testContext");
// 使用context方式
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(testUrl);
System.out.println("request line:" + httpGet.getRequestLine());
try {
// 执行get请求
HttpResponse httpResponse = client.execute(httpGet, context);
System.out.println("context cookies:"
+ context.getCookieStore().getCookies());
printResponse(httpResponse);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} @Test
public void testCookieStore() throws Exception {
System.out.println("----testCookieStore");
// 使用cookieStore方式
CloseableHttpClient client = HttpClients.custom()
.setDefaultCookieStore(cookieStore).build();
HttpGet httpGet = new HttpGet(testUrl);
System.out.println("request line:" + httpGet.getRequestLine());
try {
// 执行get请求
HttpResponse httpResponse = client.execute(httpGet);
System.out.println("cookie store:" + cookieStore.getCookies());
printResponse(httpResponse);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} 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", ""));
}
} public static void setContext() {
System.out.println("----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);
} public static void setCookieStore(HttpResponse httpResponse) {
System.out.println("----setCookieStore");
cookieStore = new BasicCookieStore();
// JSESSIONID
String setCookie = httpResponse.getFirstHeader("Set-Cookie")
.getValue();
String JSESSIONID = setCookie.substring("JSESSIONID=".length(),
setCookie.indexOf(";"));
System.out.println("JSESSIONID:" + JSESSIONID);
// 新建一个Cookie
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",
JSESSIONID);
cookie.setVersion();
cookie.setDomain("127.0.0.1");
cookie.setPath("/CwlProClient");
// 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);
} 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;
}
}

HttpClient4.x 使用cookie保持会话的更多相关文章

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

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

  2. express-12 Cookie与会话

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

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

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

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

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

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

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

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

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

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

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

  8. HttpClient4 警告: Invalid cookie header 的问题解决(转)

    原文地址:HttpClient4 警告: Invalid cookie header 的问题解决 最近使用HttpClient4的时候出现如下警告信息 org.apache.http.client.p ...

  9. 使用Cookie进行会话管理

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

随机推荐

  1. 导入google地图

    一直报地图页面的 java.lang.incompatibleclasschangeerror 想来想去,应该是包不兼容的原因,原本以为,在 build.gradle 里面 compileSdkVer ...

  2. 【PHP+Redis】 php-redis 操作类 封装

    <?php /** * redis操作类 * 说明,任何为false的串,存在redis中都是空串. * 只有在key不存在时,才会返回false. * 这点可用于防止缓存穿透 * */ cla ...

  3. const关键字浅析

    1  const变量 const double PI = 3.14159; 定义之后不能被修改,所以定义时必须初始化. const int i, j = 0; // error: i is unini ...

  4. nodeJS基础---->nodeJS的使用(一)

    Node.js是一个Javascript运行环境(runtime).实际上它是对Google V8引擎进行了封装.V8引擎执行Javascript的速度非常快,性能非常好.Node.js对一些特殊用例 ...

  5. 深入浅出Docker(五):基于Fig搭建开发环境

    概述 在搭建开发环境时,我们都希望搭建过程能够简单,并且一劳永逸,其他的同事可以复用已经搭建好的开发环境以节省开发时间.而在搭建开发环境时,我们经常会被复杂的配置以及重复的下载安装所困扰.在Docke ...

  6. Linux系统下编译连接C源代码

    gcc test.c -o test 一步到位的编译指令 得到 test 文件 gcc test.c 得到 test.out 文件 gcc -g -c test.c -o test 只生成目标文件(. ...

  7. 【Android】Android软件开发之ListView 详解

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://xys289187120.blog.51cto.com/3361352/65717 ...

  8. 【事件流】浅谈事件冒泡&&事件捕获------【巷子】

    首先在扯淡的时候我们需要先了解一个东西,这个东西就是事件流. 1.什么是事件流? 解释:当一个HTML元素触发一个事件处理函数的时候,该事件会在该元素节点到根节点之间传播,传播路径所经过的节点都会接受 ...

  9. centos7上搭建ftp服务器(亲测可用)

    1.安装vsftpd 首先要查看你是否安装vsftp [root@localhost /]# rpm -q vsftpd vsftpd-3.0.2-10.el7.x86_64 (显示以上相关信息也就安 ...

  10. c#中类和对象详解

    1.1 类和对象 类 (class) 是最基础的 C# 类型.类是一个数据结构,将状态(字段)和操作(方法和其他函数成员)组合在一个单元中.类为动态创建的类实例 (instance) 提供了定义,实例 ...