restTemplate.exchange 接口请求

一、post请求且接口参数为{"key":"value"}形式【无params参数】

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        String url_login = url+"api/user/login";
        Map param=new HashMap();
        param.put("email",usrName);
        param.put("password",passWord);
        HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSONString(param), headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url_login,
                HttpMethod.POST, formEntity, String.class);
        JSONObject body=JSONObject.parseObject(exchange.getBody());
        Assert.assertTrue(body.getString("errcode").equals("0"), "账号密码有误,登陆失败");
        //获取cookie   
   String getHeaders= String.valueOf(exchange.getHeaders().get("Set-Cookie"));
   String[] strArray = getHeaders.split(";");
   _yapi_token=strArray[0].substring(1);
   _yapi_uid=strArray[3].substring(10);
   System.out.println(_yapi_token+";"+_yapi_uid);

二、post请求且参数拼接在url

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/x-www-form-urlencoded");
        //拼接URL和参数
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("loginMobile", "17333164450")
                .queryParam("password","ls111111.");
        //封装头 //发送请求
        HttpEntity<JSONObject> request = new HttpEntity<>(null, headers);
        ResponseEntity<String> response=restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,request,String.class);
        JSONObject res=JSON.parseObject(response.getBody());//       获取返回的请求body

  

三、get请求且无参数【get请求一般需要先登录获取Cookie再请求】

        HttpHeaders headers = new HttpHeaders();
        headers.add("Cookie", Cookie);
        headers.add("Accept", "application/json, text/plain, */*");

        HttpEntity<String> formEntity = new HttpEntity<>(null, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(Url,HttpMethod.GET, formEntity, String.class);
        JSONObject body=JSONObject.parseObject(exchange.getBody());
        Assert.assertTrue(body.getString("errcode").equals("0"), "访问Yapi失败");

  

posted on 2021-06-17 17:44  jiangger  阅读(8611)  评论(0编辑  收藏  举报