·HttpClient是一款模拟客户端发送http请求的框架。
背景:用HttpClient框架请求moco接口
·GET请求
需要的moco接口:
[
{
"description": "带cookie的get请求",
"request": {
"uri": "/siteTools/app/Top",
"method": "get",
"cookies": {
"login": "true"
},
"queries": {
"year": "2013",
"week": "monday"
}
},
"response": {
"json": {
"error_code": 0,
"reason": "success",
"result": {
"SiteName": "聚合数据",
"ClassName": "综合其他、门户网站、网络科技、聚合资源",
"AreaName": "福建、厦门",
"DomainName": "chinaz.com",
"UpDate": "2019-01-20",
"Ranked": 112,
"ProvRanked": 4,
"ClassRanked": 1,
"year": 0,
"week": 3
}
}
}
},
{
"description": "get请求获取cookie值",
"request": {
"uri": "/Alexa/query.php",
"method": "get",
"queries": {
"domainName": "juhe.cn",
"key": "f29a8fff6828a81175"
}
},
"response": {
"cookies": {
"login": "true"
},
"json": {
"result": {
"DomainName": "chinaz.com",
"Title": "中国站长站",
"ShowMedianLoadTime": "1501",
"ShowPercentile": "61",
"Locale": "ZH-CN",
"Encoding": "不详",
"LinksInCount": 8017,
"PhoneNumbers": "不祥",
"Keywords": "",
"OwnedDomains": "",
"OwnerName": "不祥",
"Email": "不祥",
"Streets": "",
"City": "",
"PostalCode": null,
"Country": "",
"CompanyStockTicker": "",
"Rank": 630,
"CategoryData": {
"Title": "技术及素材/站长资源",
"AbsolutePath": "Top/World/Chinese_Simplified_CN/计算机/互联网...."
}
}
}
}
}
]
#带cookie 值请求get请求接口的三种方式
public class HttpClientApply{
//读取配置文件中的信息,ResourceBundle这个工具类,专门用于读取配置文件中的信息。
ResourceBundle bundle;
String url;
CookieStrore store;
@BeforeTest
public void readConfig(){
bundle=ResourceBundle.getBundle("cookies-apply",Locale.CHINA); //getBundle方法里放的是配置文件的名称,ResourceBundle默认识别properties文件,所以只需要写文件名就行,Locale.CHINA是编码。
url=bundle.getString("with.cookie.testurl");//通过配置文件中的键,就能获取对应的值。
}
@Test
public void getCookie(){
//获取要访问的接口地址
String testUrl=url+bundle.getString("return.cookies.testuri");
//创建URIBuilder对象,拼接请求地址与参数
URIBuilder testURI=new URIBuilder(testUrl);
testURI.setParameter("domainName","juhe.cn").setParameter( "key": "f29a8fff6828a81175");
//新建get方法对象,访问接口
HttpGet get=new HttpGet(testURI.build());
//创建CookieStore对象,用来存储cookie值;
store=new BasicCookieStore();
//获取CloseableHttpClient对象,执行请求
CloseableHttpClient httpClient=HttpClients.custom.setDefaultCookieStpre(store).build();
CloseableHttpResponse response=httpClient.execute(get);
//将响应实体转为String类型
String result=EntityUtils.toString(response.getEntity());
System.out.println(result);
//遍历cookie值
List<Cookie> list=store.getCookie();
for(Cookie cookie:list){
String name=cookie.getName();
String value=cookie.getValue;
System.out.println(name+":"+value);
}
}
//第一种,关联接口。通过CookieStore传递从上一个接口获取的cookie值,作为下一个接口请求时带上的cookie值,前提是上一个接口返回的cookie值要与下一个接口的cookie值相同。
@Test(dependsOnMethods