http请求之 RestTemplate接口请求 总结

最近做自动化测试,使用RestTemplate调用接口,碰到了各种场景下,如:
1、灵活指定调用方式
1、什么都不带的
2、带cookie、header、其他参数的
3、需要获取返回状态码的等等,先在这稍微总结下,不定期更新

一、(推荐)使用exchange指定调用方式(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 newUrl = url + "/api/queues/" + newVhost + "/" + queue;
HttpEntity<JSONObject> request = new HttpEntity<>(content,headers); //组装
ResponseEntity<String> response = template.exchange(newUrl,HttpMethod.DELETE,request,String.class);
}
二、获取接口返回状态码(Get请求)
使用getForEntity调用接口,返回结果调用getStatusCode()方法取得HttpStatus对象,然后就可以调用里面的各种方法来满足你的需求了
//判断接口返回是否为200
    public static Boolean ping(){
        String url = domain + "/it/ping";
        try{
            ResponseEntity<String> responseEntity = template.getForEntity(url,String.class);
            HttpStatus status = responseEntity.getStatusCode();//获取返回状态
            return status.is2xxSuccessful();//判断状态码是否为2开头的
        }catch(Exception e){
            return false; //502 ,500是不能正常返回结果的,需要catch住,返回一个false
        }
    }
三、什么都不带,将参数拼接在请求url后面(Post请求)
将参数拼接在请求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<Cookie> cookies = driver.manage().getCookies();//获取浏览器cookies
        List<String> cookieList = new ArrayList<String>();
        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<MultiValueMap<String,String>> request = new HttpEntity<MultiValueMap<String,String>>(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<String,String> param = new LinkedMultiValueMap<String, String>();//参数放入一个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<MultiValueMap<String,String>> request = new HttpEntity<MultiValueMap<String,String>>(param,headers);//将参数和header组成一个请求
        ResponseEntity<String> response = template.postForEntity(requestUrl, request, String.class);


    }



作者:菠了个萝
链接:https://www.jianshu.com/p/8cc05da7a6a2
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值