最近做自动化测试,使用RestTemplate调用接口,碰到了各种场景下,什么都不带的,带cookie的,带header的,带参数的,需要获取返回状态码的,先在这稍微总结下,不定期更新
一、获取接口返回状态码
使用getForEntity调用接口,返回结果调用getStatusCode()方法取得HttpStatus对象,然后就可以调用里面的各种方法来满足你的需求了
//判断接口返回是否为200
public static Boolean ping(){
String url = domain + "/it/ping";
try{
ResponseEntity responseEntity = template.getForEntity(url,String.class);
HttpStatus status = responseEntity.getStatusCode();//获取返回状态
return status.is2xxSuccessful();//判断状态码是否为2开头的
}catch(Exception e){
return false; //502 ,500是不能正常返回结果的,需要catch住,返回一个false
}
}
二、什么都不带,将参数拼接在请求url后面
将参数拼接在请求url后面,postForObject请求参数为null
public static void login(String userCode,String md5Password,int companyId,WebDriver driver){
RestTemplate template = new RestTemplate();
String url = "https://login.dooioo.net/api/autotest/userLogin";//请求地址
String param ="?userCode=" + userCode + "&md5Password=" + md5Password + "&companyId=" + companyId;
try{
String str = template.postForObject(url+param,null, String.class);//所得结果为调整成String类型
}catch(Exception e){
System.out.println("登录失败");
e.printStackTrace();
}
}
三、带cookie,header,参数
带cookie实际也是将参数塞入header中:
1、定义header对象: HttpHeaders headers = new HttpHeaders()
2、将要的cookie塞入header:headers.put(HttpHeaders.COOKIE,cookieList)(注意cookie需要是一个list,内容为 name=value 例如:loginticket=sldjfas112sadfsd)
3、也可以在Header中塞入其他值:headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED)
/*
获取浏览器的cookie,将其塞入header中
*/
public static HttpHeaders getHeader(WebDriver driver){
HttpHeaders headers = new HttpHeaders();
Set cookies = driver.manage().getCookies();//获取浏览器cookies
List cookieList = new ArrayList();
for(Cookie cookie:cookies){ //将浏览器cookies放入list中
//System.out.println("当前cookies为:" + cookie.getDomain() + " " + cookie.getName() + ":" + cookie.getValue());
cookieList.add(cookie.getName() + "=" + cookie.getValue());
}
//System.out.println("cookie为:" + cookieList.toString());
headers.put(HttpHeaders.COOKIE,cookieList); //将cookie放入header
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); //post表单 ,如果是个json则设置为MediaType.APPLICATION_JSON
return headers;
}
放入参数:
1、使用MultiValueMap用来放参数,(使用HashMap不行,具体原因可见http://www.cnblogs.com/shoren/p/RestTemplate-problem.html ),
2、根据header和参数实例化HttpEntity ,然后调用postForEntity方法调用接口
HttpEntity> request = new HttpEntity>(param,headers)
完整代码如下(使用方法可参考:https://segmentfault.com/a/1190000007778403):
public static void gitUpLoad(WebDriver driver,String uploadUrl,String fileName,String content,String branch,String requestUrl) throws Exception{
String authenticity_token = getToken(driver,uploadUrl);//获取token
RestTemplate template = new RestTemplate();
HttpHeaders headers = getHeader(driver);//获取header
MultiValueMap param = new LinkedMultiValueMap();//参数放入一个map中,restTemplate不能用hashMap
//将请求参数放入map中
param.add("authenticity_token",authenticity_token);
param.add("file_name",fileName);
param.add("encoding","text");
param.add("commit_message","addFile");
param.add("target_branch",branch);
param.add("original_branch",branch);
param.add("content",content);
param.add("utf8","✓");
//System.out.println("参数内容为:" + param.toString());
HttpEntity> request = new HttpEntity>(param,headers);//将参数和header组成一个请求
ResponseEntity response = template.postForEntity(requestUrl, request, String.class);
}
四、使用exchange指定调用方式
使用exchange方法可以指定调用方式
需要注意的一点是对于返回结果为204 no content,这种没有返回值的请求,RestTemplate会抛错,有需要的话可以使用httpClient的fluent
public void deleteQueue(String vhost,String queue){
HttpHeaders headers = new HttpHeaders();//header参数
headers.add("authorization",Auth);
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject content = new JSONObject();//放入body中的json参数
content.put("mode","delete");
content.put("name",queue);
content.put("vhost","/" + vhost);
String newVhost = "%2F" + vhost;
String newUrl = url + "/api/queues/" + newVhost + "/" + queue;
HttpEntity request = new HttpEntity<>(content,headers); //组装
ResponseEntity response = template.exchange(newUrl,HttpMethod.DELETE,request,String.class);
}