RestTemplate使用案例

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"));
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 浪费时间不如学习文学 浪费生命不如学习文学 浪费粮食不如学习文学 浪费书籍不如学习文学
    王密亮阅读 858评论 0 1
  • 可以被留在时间里
    摄影师柳丁阅读 1,144评论 0 1
  • 我要如何对自己说呢?当我的表象只是如此的时候,他人看到的是什么,我们心中的呈现又是什么?好像不清不楚,却也知道,其...
    簡清阅读 760评论 0 0