Httpclient4.5.*HttpClient请求,对于新建httpclient实例时保持会话
package net.bill99.httpconsel;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry; import org.apache.http.*;
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.Cookie;
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.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; import java.util.HashMap;
import java.util.Map; public class TestHttpClient {
// 创建CookieStore实例
static CookieStore cookieStore = null;
static HttpClientContext context = null;
static StringBuffer cookielocal= new StringBuffer();//保存cookie
String loginUrl = "http://fscposs.99bill.com/fscposs/loginProcess.htm";
String testUrl = "http://fscposs.99bill.com/fscposs/ftl/fscposs/main.jsp"; @BeforeClass
public void testLogin() throws Exception {
System.out.println("----testLogin");
// 直接创建client
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(loginUrl);
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
Map parameterMap = new HashMap();
parameterMap.put("userName", "qatest_nj");
parameterMap.put("password", "99bill99");
parameterMap.put("method","login");
parameterMap.put("tokenPWD","");
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(getParam(parameterMap), "UTF-8");
httpPost.setEntity(postEntity);
System.err.println("request line:" + httpPost.getRequestLine());
try {
// 执行post请求
HttpResponse httpResponse = client.execute(httpPost);
String location = httpResponse.getFirstHeader("Location")
.getValue();
printResponse(httpResponse); // 执行get请求
System.err.println("----the same client");
HttpGet httpGet = new HttpGet(testUrl);
System.out.println("request line:" + httpGet.getRequestLine());
HttpResponse httpResponse1 = client.execute(httpGet);
System.out.println("====main=====:" +EntityUtils.toString(httpResponse1.getEntity()));
// cookie store,保存cookie方法
setCookieStore(httpResponse); System.err.println("cookieStore值为:"+cookieStore);
// context
setContext();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} @Test
public void testCookie(){
System.err.println("=======开始执行test1======:"+cookielocal);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(testUrl);
System.err.println("cookielocal值:"+cookielocal.substring(0,cookielocal.length()-1).toString());
httpGet.setHeader("cookie",cookielocal.substring(0,cookielocal.length()-1).toString());
System.out.println("request line:" + httpGet.getRequestLine());
try {
// 执行get请求
HttpResponse httpResponse = client.execute(httpGet);
System.out.println("====main=====:" +EntityUtils.toString(httpResponse.getEntity()));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} 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());
System.out.println("====main=====:" +EntityUtils.toString(httpResponse.getEntity()));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} 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());
System.out.println("====main=====:" +EntityUtils.toString(httpResponse.getEntity()));
printResponse(httpResponse);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} public static void printResponse(HttpResponse httpResponse)
throws Exception {
// 获取响应消息实体
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();
Header[] headers = httpResponse.getHeaders("Set-Cookie");
for(Header header : headers)
{
System.out.println("----RawValue: " + header.getValue());
HeaderElement[] headerElementArray = header.getElements();
for(HeaderElement headerElement : headerElementArray)
{
System.out.print("Value=" + headerElement.getName());
// 获取cookie并保存 if(null != headerElement.getValue())
{
cookielocal.append(headerElement.getName() + "="+ headerElement.getValue()+";");
System.out.println(" key=" + headerElement.getValue());
}
BasicClientCookie cookie = new BasicClientCookie(headerElement.getName(),headerElement.getValue());
cookie.setVersion(0);
NameValuePair[] nameValuePairArray = headerElement.getParameters();
for(NameValuePair nameValuePair : nameValuePairArray)
{
System.out.println("Parameter: " + nameValuePair.getName() + " <-|-> " + nameValuePair.getValue());
switch (nameValuePair.getName()){
case "Domain" :
if(nameValuePair.getValue()!=null) {
cookie.setDomain(nameValuePair.getValue());
}
break;
case "Path":
if(nameValuePair.getValue()!=null) {
cookie.setDomain(nameValuePair.getValue());
}
break;
default:
break;
} }
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.5.*HttpClient请求,对于新建httpclient实例时保持会话的更多相关文章
- HttpClient不必每次新建实例而RestSharp推荐新建实例的原因
https://stackoverflow.com/questions/49588205/should-restclient-be-singleton-or-new-for-every-request ...
- HttpClient请求服务器代码优化版
HttpClient请求服务器代码优化版 首先,我在前面的两篇博文中介绍了在 Android中,除了使用java.net包下HttpUrlConnection的API访问HTTP服务之外,我们还可以换 ...
- Android使用HttpClient请求服务器代码优化版
首先,我在前面的两篇博文中介绍了在Android中,除了使用java.net包下HttpUrlConnection的API访问HTTP服务之外,我们还可以换一种途径去完成工作.Android SDK附 ...
- android 请求网络 和 httpclient的使用上传下载
访问网络最主要的也就是 http协议了. http协议很简单,但是很重要. 直接上代码了,里面都是1个代码块 代码块的,用哪一部分直接拷出去用就好了. 1.访问网络用 get 和 post 自己组拼 ...
- HttpClient请求详解
HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...
- JAVA发送HttpClient请求及接收请求结果
1.写一个HttpRequestUtils工具类,包括post请求和get请求 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2 ...
- C# HttpClient 请求认证、数据传输笔记
目录 一,授权认证 二,请求类型 三,数据传输 C# HttpClient 请求认证.数据传输笔记 一,授权认证 客户端请求服务器时,需要通过授权认证许可,方能获取服务器资源,目前比较常见的认证方式有 ...
- HttpClient请求
HttpClient HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包, 并且它支持 HTTP ...
- HttpClient请求返回JSON、图片
/** * Created by RongGuang on 2015/9/19. */ public class RongHttp { /** * Http Post请求 * @param url * ...
随机推荐
- Nginx的定时事件的实现(timer)
Nginx的定时事件的实现(timer) 在前面的文章里面就说到了在事件循环中除了要处理所有的从epoll中获取的事件之外,还要处理一些timer事件,这篇文章就讲讲Nginx的timer是如何实现的 ...
- Mybatis 报错 java.lang.IllegalArgumentException: Result Maps collection does not contain value for java.lang.Inte
like ‘%java.lang.IllegalArgumentException: Result Maps collection does not contain value for java.la ...
- MySQL InnoDB 存储引擎原理浅析
注:本文主要基于MySQL 5.6以后版本编写,多数知识来着书籍<MySQL技术内幕++InnoDB存储引擎>,本文章仅记录个人认为比较重要的部分,有兴趣的可以花点时间读原书. 一.MyS ...
- Docker--DockerFile创建自己的image
echo编辑整理,欢迎转载,转载请声明文章来源.欢迎添加echo微信(微信号:t2421499075)交流学习. 百战不败,依不自称常胜,百败不颓,依能奋力前行.--这才是真正的堪称强大!!! 在我们 ...
- Win32_PhysicalMedia 硬盘 参数说明
Caption 物理内存还虚拟内存 Description 描述和Caption一样 InstallDate 安装日期(无值) Name 名字 Status 状态 CreationClassName ...
- [Java并发] AQS抽象队列同步器源码解析--独占锁释放过程
[Java并发] AQS抽象队列同步器源码解析--独占锁获取过程 上一篇已经讲解了AQS独占锁的获取过程,接下来就是对AQS独占锁的释放过程进行详细的分析说明,废话不多说,直接进入正文... 锁释放入 ...
- 微信团队分享:极致优化,iOS版微信编译速度3倍提升的实践总结
1.引言 岁月真是个养猪场,这几年,人胖了,微信代码也翻了. 记得 14 年转岗来微信时,用自己笔记本编译微信工程才十来分钟.如今用公司配的 17 年款 27-inch iMac 编译要接近半小时:偶 ...
- JS获取包含当前节点本身的代码内容(outerHtml)
原生JS DOM的内置属性 outerHTML 可用来获取当前节点的html代码(包含当前节点),且此属性可使用jQuery的prop()获取 <div id="demo-test-0 ...
- adb 获取平台号
获取 Android 的 PLATFORM_VERSION :adb shell getprop ro.build.version.release获取 Android 的 APP_PACKAGE 和 ...
- Nginx核心流程及模块介绍
Nginx核心流程及模块介绍 1. Nginx简介以及特点 Nginx简介: Nginx (engine x) 是一个高性能的web服务器和反向代理服务器,也是一个IMAP/POP3/SMTP服务器 ...