HttpClient4.5.2官方文档
HttpClient不是浏览器。它是一个客户端的HTTP通信库。HttpClient的目的是,以编程的方式通过其API传输和接收HTTP消息。
一、特征
-
基于标准、纯净的java语言。实现了Http1.0和Http1.1
-
以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
-
支持HTTPS协议。
-
通过Http代理建立透明的连接。
-
利用CONNECT方法通过Http代理建立隧道的https连接。
-
Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。
-
插件式的自定义认证方案。
-
便携可靠的套接字工厂使它更容易的使用第三方解决方案。
-
连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。
-
自动处理Set-Cookie中的Cookie。
-
插件式的自定义Cookie策略。
-
Request的输出流可以避免流中内容直接缓冲到socket服务器。
-
Response的输入流可以有效的从socket服务器直接读取相应内容。
-
在http1.0和http1.1中利用KeepAlive保持持久连接。
-
直接获取服务器发送的response code和 headers。
-
设置连接超时的能力。
-
实验性的支持http1.1 response caching。
-
源代码基于Apache License 可免费获取。
参见http client 4.5主页
二、引入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.10</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20170516</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
三、使用大致步骤
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
-
创建HttpClient对象。
-
创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
-
如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
-
调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
-
调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容,程序可通过该对象获取服务器的响应内容。
-
释放连接。无论执行方法是否成功,都必须释放连接
四、举例之get
下面get/post案例中的url和uri,均使用application.properties配置文件的参数
test.url=http://localhost:8888
test.getCookies.uri=/getCookies
test.get.with.cookies.uri=/get/withCookies
test.simple.post.uri=/simplePost
test.post.with.param.forms.uri=/postwithparam/forms
test.post.with.param.json.uri=/postwithparam/json
test.post.with.cookies.uri=/post/withCookies
例1-get请求
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;
import java.io.IOException;
public class SimpleGet {
@Test
public void test1() throws IOException {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http GET请求
HttpGet httpGet = new HttpGet("http://www.baidu.com");
CloseableHttpResponse response = null; //响应
try {
//执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200){
//请求体内容
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(result);
}
} finally {
if (response != null){
response.close();
}
//相当于关闭浏览器
httpclient.close();
}
}
}
执行test1,结果如下:
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a> 京ICP证030173号 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
例2-get请求带参数
package com.course.httpclient.demo;
import java.io.File;
import java.net.URI;
import org.apache.commons.io.FileUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* 带参数的GET请求
* 两种方式:
* 1.直接将参数拼接到url后面 如:?wd=java
* 2.使用URI的方法设置参数 setParameter("wd", "java")
*/
public class DoGETParam {
public static void main(String[] args) throws Exception {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 定义请求的参数
URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
//response 对象
CloseableHttpResponse response = null;
try {
// 执行http get请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
//内容写入文件
FileUtils.writeStringToFile(new File("E:\\javatest\\baidu-param.html"), content, "UTF-8");
System.out.println("内容长度:"+content.length());
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
}
}
例2-get请求获取cookie
使用moco,模拟一个返回cookie的get请求
[ {
"description": "这是一个会返回cookies信息的get请求",
"request": {
"uri": "/getCookies",
"method": "get"
},
"response": {
"headers": {
"Content-Type": "text/html;charset=gbk"
},
"cookies": {
"login": "true"
},
"text": "恭喜你获得cookies信息"
}
}
]
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
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.util.EntityUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class GetAndCookies {
private ResourceBundle bundle; //从.properties文件读取配置
private String url;
private CookieStore cookieStore;//用来存储cookies信息的变量
@BeforeTest
public void beforeTest(){
bundle = ResourceBundle.getBundle("application", Locale.CHINA);
this.url = bundle.getString("test.url");
}
@Test
public void testGetCookies() throws IOException {
//创建httpClient对象
this.cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
//拼接url
String uri =bundle.getString("test.getCookies.uri");
String testUrl = this.url + uri;
// 创建http GET请求
HttpGet httpGet = new HttpGet(testUrl);
CloseableHttpResponse response = null; //响应
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200){
String result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
//获取cookies信息
List<Cookie> cookieList = this.cookieStore.getCookies();
for (Cookie cookie : cookieList){
String name = cookie.getName();
String value = cookie.getValue();
System.out.println("cookie name = " + name + "; cookie value = " + value);
}
}
} finally {
if (response != null){
response.close();
}
//相当于关闭浏览器
httpClient.close();
}
}
}
执行testGetWithCookies(),结果为
恭喜你获得cookies信息
cookie name = login; cookie value = true
===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
例3-get请求带cookie
[
{
"description": "这是一个会返回cookies信息的get请求",
"request": {
"uri": "/getCookies",
"method": "get"
},
"response": {
"headers": {
"Content-Type": "text/html;charset=gbk"
},
"cookies": {
"login": "true"
},
"text": "恭喜你获得cookies信息"
}
},
{
"description": "这是一个带cookies信息的get请求",
"request": {
"uri": "/get/withCookies",
"method": "get",
"cookies": {
"login": "true"
}
},
"response": {
"headers": {
"Content-Type": "text/html;charset=gbk"
},
"text": "这是一个需要携带cookies信息才能访问的get请求"
}
}
]
package com.course.httpclient.cookies;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
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.util.EntityUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class GetAndCookies {
private ResourceBundle bundle; //从.properties文件读取配置
private String url;
private CookieStore cookieStore;//用来存储cookies信息的变量
@BeforeTest
public void beforeTest(){
bundle = ResourceBundle.getBundle("application", Locale.CHINA);
this.url = bundle.getString("test.url");
}
@Test
public void testGetCookies() throws IOException {
//创建httpClient对象
this.cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
//拼接url
String uri =bundle.getString("test.getCookies.uri");
String testUrl = this.url + uri;
// 创建http GET请求
HttpGet httpGet = new HttpGet(testUrl);
CloseableHttpResponse response = null; //响应
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200){
String result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
//获取cookies信息
List<Cookie> cookieList = this.cookieStore.getCookies();
for (Cookie cookie : cookieList){
String name = cookie.getName();
String value = cookie.getValue();
System.out.println("cookie name = " + name + "; cookie value = " + value);
}
}
} finally {
if (response != null){
response.close();
}
//相当于关闭浏览器
httpClient.close();
}
}
@Test(dependsOnMethods = {"testGetCookies"})
public void testGetWithCookies() throws IOException {
//创建httpClient
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(this.cookieStore).build();
String uri = bundle.getString("test.get.with.cookies.uri");
String testUrl = this.url + uri;
// 创建http GET请求
HttpGet httpGet = new HttpGet(testUrl);
CloseableHttpResponse response = null; //响应
//设置cookies信息
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(result);
}
} finally {
if (response != null){
response.close();
}
httpClient.close();
}
}
}
执行testGetWithCookies(),结果如下
恭喜你获得cookies信息
cookie name = login; cookie value = true
这是一个需要携带cookies信息才能访问的get请求
===============================================
Default Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================
五、举例之post
例1-post请求
使用moco模拟的post请求
[{
"description": "这是一个没有参数的post请求",
"request": {
"uri": "/postdemo",
"method": "post"
},
"response": {
"headers": {
"Content-Type": "text/html;charset=gbk"
},
"text": "这是mock的post请求"
}
}]
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;
public class SimplePost {
private String url;
private ResourceBundle bundle;
@BeforeTest
public void beforeTest(){
bundle = ResourceBundle.getBundle("application", Locale.CHINA);
url = bundle.getString("test.url");
}
@Test
public void test1() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
String uri = bundle.getString("test.simple.post.uri");
String testUrl = url + uri;
HttpPost httpPost = new HttpPost(testUrl);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200){
String result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(result);
}
} finally {
if (response != null){
response.close();
}
httpClient.close();
}
}
}
执行test1,结果如下
这是mock的post请求
===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
例2-post请求带forms参数
使用moco模拟的带参数的post请求
[ {
"description": "这是一个带参数的post请求",
"request": {
"uri": "/postwithparam",
"method": "post",
"forms": {
"name": "zhangsan",
"age": "18"
}
},
"response": {
"headers": {
"Content-Type": "text/html;charset=gbk"
},
"text": "我是张三!"
}
}
]
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class SimplePost {
private String url;
private ResourceBundle bundle;
@BeforeTest
public void beforeTest(){
bundle = ResourceBundle.getBundle("application", Locale.CHINA);
url = bundle.getString("test.url");
}
@Test
public void test2() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
String uri = bundle.getString("test.post.with.param.forms.uri");
String testUrl = url + uri;
HttpPost httpPost = new HttpPost(testUrl);
//post请求传参有3种方式
// 表单方式
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
parameters.add(new BasicNameValuePair("name", "zhangsan"));
parameters.add(new BasicNameValuePair("age", "18"));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 将请求实体设置到httpPost对象中
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(result);
} finally {
if (response != null){
response.close();
}
httpClient.close();
}
}
}
执行test2() ,结果如下:
我是张三!
===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
例3-post请求带json参数
使用moco模拟的带参数的post请求
[ {
"description": "这是一个参数为json的post请求",
"request": {
"uri": "/postwithparam/json",
"method": "post",
"json": {
"name": "zhangsan",
"age": "18"
}
},
"response": {
"headers": {
"Content-Type": "text/html;charset=gbk"
},
"json": {
"zhangsan": "success",
"status": "1"
}
}
}
]
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class SimplePost {
private String url;
private ResourceBundle bundle;
@BeforeTest
public void beforeTest(){
bundle = ResourceBundle.getBundle("application", Locale.CHINA);
url = bundle.getString("test.url");
}
@Test
public void test3() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
String uri = bundle.getString("test.post.with.param.json.uri");
String testUrl = url + uri;
HttpPost httpPost = new HttpPost(testUrl);
//post请求传参有2种方式,json方式和表单方式
// json方式
JSONObject jsonParam = new JSONObject();
jsonParam.put("name", "zhangsan");
jsonParam.put("age", "18");
StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(result);
//将返回的响应结果字符串转化成为json对象
JSONObject resultJson = new JSONObject(result);
//获取到结果值
String success = (String) resultJson.get("zhangsan");
String status = (String) resultJson.get("status");
//具体的判断返回结果的值
Assert.assertEquals("success",success);
Assert.assertEquals("1",status);
} finally {
if (response != null){
response.close();
}
httpClient.close();
}
}
}
执行test3(),结果如下:
{"zhangsan":"success","status":"1"}
===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
例4-post请求带cookie,且参数使用json
[ {
"description": "这是一个会返回cookies信息的get请求",
"request": {
"uri": "/getCookies",
"method": "get"
},
"response": {
"headers": {
"Content-Type": "text/html;charset=gbk"
},
"cookies": {
"login": "true"
},
"text": "恭喜你获得cookies信息"
}
},
{
"description": "这是一个带cookies信息的post请求",
"request": {
"uri": "/post/withCookies",
"method": "post",
"cookies": {
"login": "true"
},
"json": {
"name": "zhangsan",
"age": "18"
}
},
"response": {
"status": 200,
"json": {
"zhangsan": "success",
"status": "1"
}
}
}
]
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
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.util.EntityUtils;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class PostAndCookies {
private ResourceBundle bundle; //从.properties文件读取配置
private String url;
private CookieStore cookieStore;//用来存储cookies信息的变量
@BeforeTest
public void beforeTest(){
bundle = ResourceBundle.getBundle("application", Locale.CHINA);
this.url = bundle.getString("test.url");
}
@Test
public void testGetCookies() throws IOException {
//创建httpClient对象
this.cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
//拼接url
String uri =bundle.getString("test.getCookies.uri");
String testUrl = this.url + uri;
// 创建http GET请求
HttpGet httpGet = new HttpGet(testUrl);
CloseableHttpResponse response = null; //响应
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200){
String result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
//获取cookies信息
List<Cookie> cookieList = this.cookieStore.getCookies();
for (Cookie cookie : cookieList){
String name = cookie.getName();
String value = cookie.getValue();
System.out.println("cookie name = " + name + "; cookie value = " + value);
}
}
} finally {
if (response != null){
response.close();
}
//相当于关闭浏览器
httpClient.close();
}
}
@Test(dependsOnMethods = {"testGetCookies"})
public void testPostWithCookies() throws IOException {
//手动增加cookie
/*CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("login", "true");
cookie.setDomain("localhost");
cookie.setPath("/");
cookieStore.addCookie(cookie);
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();*/
//创建httpClient,cookie由/getCookies接口获取
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(this.cookieStore).build();
String uri = bundle.getString("test.post.with.cookies.uri");
String testUrl = this.url + uri;
// 创建http POST请求
HttpPost httpPost = new HttpPost(testUrl);
//post请求传参有2种方式,json方式和表单方式
// json方式
JSONObject jsonParam = new JSONObject();
jsonParam.put("name", "zhangsan");
jsonParam.put("age", "18");
StringEntity entity = new StringEntity(jsonParam.toString(),"UTF-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
CloseableHttpResponse response = null; //响应
//设置cookies信息
try {
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200){
String result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("++++++++++++++++++++++");
System.out.println(result);
JSONObject resultJson = new JSONObject(result);
//获取到结果值
String success = (String) resultJson.get("zhangsan");
String status = (String) resultJson.get("status");
//具体的判断返回结果的值
Assert.assertEquals("success",success);
Assert.assertEquals("1",status);
}
} finally {
if (response != null){
response.close();
}
//相当于关闭浏览器
httpClient.close();
}
}
}
执行testPostWithCookies,结果如下
恭喜你获得cookies信息
cookie name = login; cookie value = true
++++++++++++++++++++++
{"zhangsan":"success","status":"1"}
===============================================
Default Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================
参考:
HttpClient获取Cookie的两种方式
HttpClient发送get请求,post请求,携带cookie访问,json提交