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失败");
    

      

  • 相关阅读:
    x01.JavaHello
    x01.Weiqi.1 提子算法
    x01.Weiqi.3 网络对弈
    Cryptography
    Javascript判断中文字节
    asp.net mvc,asp.net4.0空间出售
    Sql Server中判断日志是否为一个星期
    DIV+CSS实现二级导航菜单
    ExecutorService线程池 [转]
    Android程序开发所用app图标的几种大小
  • 原文地址:https://www.cnblogs.com/jiangger/p/14894626.html
Copyright © 2011-2022 走看看