HttpClient4.x可以自带维持会话功能,只要使用同一个HttpClient且未关闭连接,则可以使用相同会话来访问其他要求登录验证的服务(见TestLogin()方法中的“执行get请求”部分)。

如果需要使用HttpClient池,并且想要做到一次登录的会话供多个HttpClient连接使用,就需要自己保存会话信息。因为客户端的会话信息是保存在cookie中的(JSESSIONID),所以只需要将登录成功返回的cookie复制到各个HttpClient使用即可。使用Cookie的方法有两种,可以自己使用CookieStore来保存(见TestCookieStore()方法),也可以通过HttpClientContext上下文来维持(见TestContext()方法)。

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(0);
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;
}
}

httpclient 登录成功后返回的cookie值访问下一页面的更多相关文章

  1. httpclient 怎么带上登录成功后返回的cookie值访问下一页面

    我是只很菜很菜的小鸟.刚上班,有这个一个需求.要我抓取别的网站的数据.     我根据用户密码登录一个网站成功后,生成一个cookie值.我已经获取到了.然后要带上这个cookie值进行下一页面的访问 ...

  2. 在某网站的登录页面登录时如果选择“记住用户名”,登录成功后会跳转到一个中间层(页面代码将登录的用户名和密码存在cookie),中间页面中存在一个超链接,单击超链接可以链接到第三个页面查看信息。若选择“

    Response实现登录并记录用户名和密码信息 在某网站的登录页面登录时如果选择"记住用户名",登录成功后会跳转到一个中间层(页面代码将登录的用户名和密码存在cookie),中间页 ...

  3. 登录成功后如何利用cookie保持登录状态

    Cookie是一种服务器发送给浏览器的一组数据,用于浏览器跟踪用户,并访问服务器时保持登录状态等功能. 通常用户登录的时候,服务器根据用户名和密码在服务器数据库中校验该用户是否正确,校验正确后则可以根 ...

  4. [原]基于CAS实现单点登录(SSO):登录成功后,cas client如何返回更多用户信息

    从cas server登录成功后,默认只能从casclient得到用户名.但程序中也可能遇到需要得到更多如姓名,手机号,email等更多用户信息的情况. cas client拿到用户名后再到数据库中查 ...

  5. IE9中ajax请求成功后返回值却是undefined

    ie9中ajax请求一般处理程序成功后返回值始终是undefined,在网上找过很多资料,大致意思都是说前后端编码不一致造成的,但是按照资料上的方案去修改却发现根本不能解决我的问题,试过好多种方案都不 ...

  6. 单点登录(十七)----cas4.2.x登录mongodb验证方式成功后返回更多信息更多属性到客户端

    我们在之前已经完成了cas4.2.x登录使用mongodb验证方式登录成功了.也解决了登录名中使用中文乱码的问题. 单点登录(十三)-----实战-----cas4.2.X登录启用mongodb验证方 ...

  7. 使用Shiro登录成功后,跳转到之前访问的页面实现

    转:http://blog.csdn.net/lhacker/article/details/20450855 很多时候,我们需要做到,当用户登录成功后,跳转回登录前的页面.如果用户是点击" ...

  8. [saiku] 系统登录成功后查询Cubes

    一.系统启动时初始化ds和conn 1.查询出目前系统拥有的Datasources和Connections放入内存中 2.比对saiku-datasources中的ds是否有新增的,如果有,创建新的d ...

  9. 【转】【可用】Android 登录判断器,登录成功后帮你准确跳转到目标activity

    我们在使用应用时肯定遇到过这样的情景,打开应用,并不是需要我们登录,你可以浏览应用中的大部分页面,但是当你想看某个详情页的时候,点击后突然跳转到了登录页面,好,我们输入账号密码,点击登录,登录成功,跳 ...

随机推荐

  1. NOIP模拟「random·string·queen」

    T1:random   我又来白剽博客了:   详细证明请看土哥   土哥写的不是很详细,我在这里详细写一下:   首先,对于f[n]的式子:   加一是那一个对的贡献,大C是选其余的几个数,\(2^ ...

  2. Docker Note1——架构和三要素

    Docker官方文档: https://docs.docker.com/ 一.docker架构 C/S架构,主要由 client / daemon / containers / images 组成. ...

  3. SpingBoot-Dubbo-Zookeeper-分布式

    目录 分布式理论 什么是分布式系统? Dubbo文档 单一应用架构 垂直应用架构 分布式服务架构 流动计算架构 什么是RPC RPC基本原理 测试环境搭建 Dubbo Dubbo环境搭建 Window ...

  4. 解决git bash闪退问题 报openssl错误

    问题描述:今天安装git之后发现Git Bash工具闪退. 于是试了各种办法之后,最后终于解决. 背景描述:git 下载地址:https://git-scm.com/download/win 下载成功 ...

  5. Grid 网格布局详解

    Grid网格布局详解: Grid布局与Flex布局有着一定的相似性,Grid布局是将容器划分成行和列,产生单元格,可以看做是二维布局. 基本概念: 采用网格布局的区域,称为"容器" ...

  6. 在PHP中如何为匿名函数指定this?

    在之前的文章中,我们已经学习过匿名函数的使用,没有看过的小伙伴可以进入传送门先去了解下闭包匿名函数的用法,传送:还不知道PHP有闭包?那你真OUT了. 关于闭包匿名函数,在JS中有个很典型的问题就是要 ...

  7. javascript,jquery在父窗口触发子窗口(iframe)某按钮的click事件

    $('iframe').contents().find(".btn").click(); 其中 contents(): 查找匹配元素内部所有的子节点(包括文本节点).如果元素是一个 ...

  8. Influxdb数据库 - 基本操作

    InfluxDB数据库的简介 InfluxDB是一个用于存储和分析时间序列数据的开源数据库,是一个基于 golang 编写,用于记录 metrics.events,进行数据分析. 主要特性有: 内置H ...

  9. Xftp乱码问题

    Xftp出现乱码 修改编码

  10. navicat导出DDL语句

    工作中有的时候需要将某个库中的表.视图.函数.存储过程等创建语句导出,又不需要表中的数据. 方法一:需要拷贝的创建语句条数不多,可以选择直接拷贝DDL语句 方法二:使用Navicat的备份功能