美文网首页
RestTemplate使用案例

RestTemplate使用案例

作者: 程序界小白 | 来源:发表于2018-10-17 11:17 被阅读0次

    RestTemplate使用案例

    1. POST
    • Content-Type application/x-www-form-urlencoded
    MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
            postParameters.add("userCode", "291974");
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/x-www-form-urlencoded");
            HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(postParameters, headers);
    
            String data= restTemplate.postForObject("http://10.10.12.27:9000/Criteria", r, String.class);
            System.out.println(data);
    
    • Content-Type application/json;charset=UTF-8
    public Response modifyPersonalPhone(ModifyPersonalPhoneRequest request) throws JsonProcessingException {
            String url = server.concat("/ModifyPersonalPhone");
            try {
                //  一定要设置header
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                ObjectMapper mapper = new ObjectMapper();
                String value = mapper.writeValueAsString(request);
                HttpEntity<String> requestEntity = new HttpEntity<String>(value, headers);
                return template.postForEntity(url, requestEntity, ModifyPersonalPhoneResponse.class).getBody();
            }catch (RestClientResponseException e){
                JSONObject jsonObject = JSONObject.parseObject(e.getResponseBodyAsString());
                throw Exceptions.createCloudServiceErrorException(e.getRawStatusCode(),(String)jsonObject.get("code"), (String)jsonObject.get("message"));
            }
        }
    

    2.GET

    public Response resetPersonalPasswordByPhone(ResetPersonalPasswordByPhoneRequest request) {
            String url = server.concat("/ResetPersonalPasswordByPhone?phoneNumber={phoneNumber}&phoneCode={phoneCode}&phoneBizId={phoneBizId}&password={password}&state={state}");
            try {
                return template.getForObject(url, ResetPersonalPasswordByPhoneResponse.class, ObjectToMapUtil.obj2Map(request));
            }catch (RestClientResponseException e){
                JSONObject jsonObject = JSONObject.parseObject(e.getResponseBodyAsString());
                throw Exceptions.createCloudServiceErrorException(e.getRawStatusCode(),(String)jsonObject.get("code"), (String)jsonObject.get("message"));
            }
        }

    相关文章

      网友评论

          本文标题:RestTemplate使用案例

          本文链接:https://www.haomeiwen.com/subject/oevlzftx.html