[
{
"description":"这是一个带cookies信息的get请求",
"request":{
"uri":"/getcookies",
"method":"get"
},
"response":{
"cookies":{
"login":"true"
},
"text":"获得cookies信息成功"
}
},
{
"description":"这是一个带cookies信息的get请求",
"request":{
"uri":"/get/with/cookies",
"method":"get",
"cookies":{
"login":"true"
}
},
"response":{
"text":"这是一个需要携带cookies信息才能访问的get请求"
}
}
]
我们要做的是从/getcookies接口中获取”login”:”true”的cookies信息,然后携带该信息去访问/get/with/cookies接口
resource目录下新建application.properties文件,文件内配置访问接口的url和路径
test.url=http://localhost:8899
test.getcookies.uri=/getcookies
test.get.with.cookies=/get/with/cookies
从配置文件中读取url,以及准备储存cookies信息的变量
private String url;
private ResourceBundle bundle;
//用来存取cookies信息的变量
private CookieStore store;
@BeforeTest
public void beforeTest(){
bundle = ResourceBundle.getBundle("application",Locale.CHINA);
url = bundle.getString("test.url");
}
@Test
public void testGetCookies() throws IOException {
//从配置文件中,提取并拼接url
String uri = bundle.getString("test.getcookies.uri");
String testUrl = this.url+uri;
//获取body
String result;
HttpGet get = new HttpGet(testUrl);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
//获取cookies信息
this.store = client.getCookieStore();
List cookieList = store.getCookies();
for (Cookie cookie : cookieList){
String name =cookie.getName();
String value = cookie.getValue();
System.out.println("访问/getcookies接口成功,cookie name = "+name+", cookie value = "+value);
}
}
@Test(dependsOnMethods = {"testGetCookies"})
public void testGetWithCookies() throws IOException {
//从配置文件中,提取并拼接url
String uri = bundle.getString("test.get.with.cookies");
String testUrl = this.url+uri;
HttpGet get = new HttpGet(testUrl);
DefaultHttpClient client = new DefaultHttpClient();
//设置cookies信息
client.setCookieStore(this.store);
HttpResponse response =client.execute(get);
//获取相应状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("statusCode = "+statusCode);
if (statusCode==200){
String result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
}
else {
System.out.println("访问/get/with/cookies接口失败");
}
}