zoukankan      html  css  js  c++  java
  • 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失败");
    

      

  • 相关阅读:
    阿里云 MaxCompute 2019-12 月刊
    【原】react+redux实战
    【原】http缓存与cdn相关技术
    【原】redux异步操作学习笔记
    【原】javascript最佳实践
    【原】react做tab切换的几种方式
    【原】web移动端常用知识点笔记
    【原】移动端界面的适配
    【原】js检测移动端横竖屏
    【原】javascript数组操作
  • 原文地址:https://www.cnblogs.com/jiangger/p/14894626.html
Copyright © 2011-2022 走看看