RestTemplate发起POST请求,json参数小坑

原来的代码

public JSONObject temlateUtil(MultiValueMap params,String pathUrl){
        RestTemplate restTemplate = new RestTemplate();
        String url = String.format(pathUrl);
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        //将请求头部和参数合成一个请求
        HttpEntity> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求,将返回的结构使用ResultVO类格式化
        ResponseEntity response = restTemplate.exchange(url, method, requestEntity, String.class);

        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        return jsonObject;

    }

这样好像可以获取返回,但断点后,会发现传送的参数并不是json格式,而是类似于数组的格式,所以会识别不了属性内的参数。

新代码

JSONObject json = new JSONObject();
        json.put("userName", addRequestDto.getEmpName());
        json.put("empno", addRequestDto.getEmpNo());
        json.put("msisdn", addRequestDto.getMsisdn());
        json.put("branchationgroup", addRequestDto.getBranchationgroup());
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity formEntity = new HttpEntity(json.toString(), headers);
        String s= restTemplate.postForEntity(SsmnUrl.HOME_REGISTUSER,formEntity,String.class).getBody();


这样也不对,

再换一种

RestTemplate restTemplate = new RestTemplate();
        String url = String.format(SsmnUrl.HOME_REGISTUSER);
        HttpHeaders headers = new HttpHeaders();
        //HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        RegistNewDto registNewDto =  new RegistNewDto();
        registNewDto .setUserName(addRequestDto.getEmpName());
        registNewDto .setMsisdn(addRequestDto.getMsisdn());
        registNewDto .setEmpno(addRequestDto.getEmpNo());
        registNewDto .setBranchationgroup(addRequestDto.getBranchationgroup());

        //将请求头部和参数合成一个请求
        HttpEntity httpEntity = new HttpEntity(registNewDto , headers);
        //执行HTTP请求,将返回的结构使用ResultVO类格式化
        ResponseEntity responseEntity = restTemplate.postForEntity(url ,httpEntity, String.class);

        JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
        AddReponseDto addReponseDto = new AddReponseDto();
        addReponseDto.setCode(jsonObject.getIntValue("code"));
        addReponseDto.setMsg(jsonObject.getString("msg"));
        addReponseDto.setData(jsonObject.getString("data"));

发起get请求

RestTemplate restTemplate = new RestTemplate();
  String result=restTemplate.getForObject(webConfig.getWebapiCCHR()+"?pageIndex=1&pageSize=10&token=test&empNo="+"SC19004660",String.class);
  

你可能感兴趣的:(RestTemplate发起POST请求,json参数小坑)