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 * ...
随机推荐
- 【Web技术】314- 前端组件设计原则
点击上方"前端自习课"关注,学习起来~ 译者:@没有好名字了译文:https://github.com/lightningminers/article/issues/36,http ...
- 了解web漏洞-sql注入
1:为什么要学web漏洞? 作为一个运维人员,日常工作就是保障服务器和网站的业务正常运行,平时也需要对服务器的安全工作加固,说到防护攻击问题,那么久必须去了解攻击者是怎么对服务器发动的一个流程,这样才 ...
- 进程-(process)、线程-(Thread)
进程和线程之间的区别: 内存之间的区别: 进程之间不可以共享内存空间,每个进程都有各自独立的内存空间: 线程之间则是可以共享一个进程里的内存空间: 通信机制方面的区别 默认情况下,进程之间很难互通的, ...
- 想要金九银十面试通关,不懂 Java多线程肯定是不行的!
作者 | 纳达丶无忌 如果对什么是线程.什么是进程仍存有疑惑,请先 Google 之,因为这两个概念不在本文的范围之内. 用多线程只有一个目的,那就是更好的利用 CPU 的资源,因为所有的多线程代码都 ...
- java面试题干货51-95
51.类ExampleA继承Exception,类ExampleB继承ExampleA. 有如下代码片断: try { throw new ExampleB("b") } catc ...
- 获取浏览器视口高度device-width
在进行移动设备web开发时,我们总会用到这样一条代码“<meta name='viewport' content='width=device-width,initial-scale=1.0' / ...
- Microsemi Libero使用技巧——使用命令行模式下载程序
前言 在工程代码编译完成之后,如果需要给某个芯片下载程序时,或者是工厂量产烧录程序时,我们不需要把整个工程文件给别人,而只需要把生成的下载文件给别人,然后使用FlashPro就可以单独下载程序文件了. ...
- 全字段多条件搜索(api接口)
近期在做项目时遇到了一个全表全字段多条件搜索的需求,在平时搜索最常见的就是 字段+like +‘% 条件%’这种模式,但遇到多条件多字段时,这种就不适用了. 表字段已知,条件未知,条件数量未知,这种情 ...
- Python--合并2个字典成1个新字典的9种方法
d1 = {'name': 'revotu', 'age': 99} d2 = {'age': 24, 'sex': 'male'} 输出: {'name': 'revotu', 'age': 24, ...
- JS---DOM---为同一个元素绑定多个不同事件指向同一个事件处理函数
为同一个元素绑定多个不同事件指向同一个事件处理函数 1. 用了switch(e.type){} 来修改 2. break <input type="button" value ...