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. 20210720 noip21

    又是原题,写下题解吧 Median 首先时限有 2s(学校评测机太烂,加到 4s 了),可以放心地筛 \(1e7\) 个质数并算出 \(s_2\),然后问题变为类似滑动求中位数.发现 \(s_2\) ...

  2. Python - 头部解析

    背景 写 python 的时候,基本都要加两个头部注释,这到底有啥用呢? #!usr/bin/env python # -*- coding:utf-8 _*- print("hello-w ...

  3. Python - 导入的位置

    导入的是什么 导入是将 Python 的一些功能函数放到当前的脚本中使用 不导入的功能无法直接在当前脚本使用(除了 python 自带的内置函数) Python 有很多第三方功能,假设想要使用,都必须 ...

  4. Mysql常用sql语句(5)- as 设置别名

    测试必备的Mysql常用sql语句系列 https://www.cnblogs.com/poloyy/category/1683347.html 需要注意,创建数据库和创建表的语句博文都在前面哦 整个 ...

  5. 数据治理中Oracle SQL和存储过程的数据血缘分析

    数据治理中Oracle SQL和存储过程的数据血缘分析   数据治理中的一个重要基础工作是分析组织中数据的血缘关系.有了完整的数据血缘关系,我们可以用它进行数据溯源.表和字段变更的影响分析.数据合规性 ...

  6. linux 命令进阶篇之二

    一.预备知识 选取init的进程. cat :由第一行开始显示文件内容 tac:由最后一行开始显示,有没有发现和cat是反过来写的 more:一页一页的显示内容 less:与more相似,但是可以往前 ...

  7. vue-element-admin 全局loading加载等待

    最近遇到需求: 全局加载loading,所有接口都要可以手动控制是否展示加载等待的功能 当拿到这个需求的时候我是拒绝的,因为我以及局部写好了0.0,这是要大改呀....,没办法老板的要求,只能硬着头皮 ...

  8. 一文搞懂如何使用Node.js进行TCP网络通信

    摘要: 网络是通信互联的基础,Node.js提供了net.http.dgram等模块,分别用来实现TCP.HTTP.UDP的通信,本文主要对使用Node.js的TCP通信部份进行实践记录. 本文分享自 ...

  9. 驱动IO模型-select

    新人学习,欢迎指正 部分select.c代码 应用层 select(maxfd+1,&rfds,NULL,NULL,NULL); -------------------(系统调用)------ ...

  10. TP5 pc和wap跳转404

    在config.php中配置 // HttpException异常 'http_exception_template' => [ // 定义404错误的重定向页面地址 404 => isW ...