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 * ...
随机推荐
- USB3.0之高速视频传输测试 双目相机(mt9p031、mt9m001)带宽高达300M测试 配合isensor测试 500万像素15fps
最近完善了下USB3.0的视频开发测试,主要优化了FPGA程序和固件,及其同步方式.对带宽和图像效果进行了仔细的测试 开发板架构(2CMOS+FPGA+2DDR2+USB3.0) 评估板底板配合2个M ...
- vue2.5 + element UI el-table 导出Excel
安装依赖 npm install --save xlsx file-saver 新建excelHelper.js \src\utils\目录下新建excelHelper.js文件 import Vue ...
- 每周一练 之 数据结构与算法(LinkedList)
这是第三周的练习题,原本应该先发第二周的,因为周末的时候,我的母亲大人来看望她的宝贝儿子,哈哈,我得带她看看厦门这座美丽的城市呀. 这两天我抓紧整理下第二周的题目和答案,下面我把之前的也列出来: 1. ...
- 【MyBatis】配置文件提示
[MyBatis]配置文件提示 官方帮助文档:http://www.mybatis.org/mybatis-3/zh/index.html config配置 http://mybatis.org/dt ...
- 关于爬取babycenter.com A-Z为顺序的所有英文名及其详细属性
这一次爬取的内容已经在标题里提到了,下面是详细要求及其图示: 1.首先以A-Z的顺序获取所有英文名,最后爬取该英文名的详细信息. 2.CSV的header以3中的单词为准,请别拼错.如果没有对应的数 ...
- Fuchsia文章汇总
今日,windows时代的十年已经过去,android/ios时代的十年也行将结束,下一个十年是谁的十年? 操作系统做为软件的基石,做为基础服务的基础,因为各层应用框架的层层封装,正在变的越来越透明, ...
- IT兄弟连 HTML5教程 响应式网站的内容设计
基于响应式开发网站,除了页面的布局是我们设计的重点,网站中显示的图片和文字也是我们不能轻视的内容. 1 响应式图片显示内容设计 真正具有响应性的Web设计是完全调整网站以满足访问者的设备.我们需要在 ...
- 使用docker运行dotnetcore站点
使用docker运行netcore站点 1.新建一.netcore测试站点,dotnet publish 发布到publish目录下 2.编写Dockerfile文件 3.打包上传到centos服务器 ...
- JavaWeb学习——页面跳转方式
JavaWeb学习——页面跳转方式 摘要:本文主要学习了请求转发和响应重定向,以及两者之间的区别. 请求转发 相关方法 使用HttpServletRequest对象的 getRequestDispat ...
- Java 商户管理系统 客户管理 库存管理 销售报表 SSM项目源码
系统介绍: 1.系统采用主流的 SSM 框架 jsp JSTL bootstrap html5 (PC浏览器使用) 2.springmvc +spring4.3.7+ mybaits3.3 SSM ...