RestTemplate使用案例
- 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"));
}
}
网友评论