RestTemplate的用法总结
Posted pro-wall-box
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RestTemplate的用法总结相关的知识,希望对你有一定的参考价值。
1.post
(1)带header
public static String postUrlWithHeader(RestTemplate restTemplate, String url, HeaderModel header, String json) throws Exception{
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType("UTF-8");
HttpEntity<String> requestEntity = new HttpEntity<String>(json, requestHeaders);
ResponseEntity<String> res = restTemplate.postForEntity(url, requestEntity , String.class);
String temp2 = null;
if(res.getStatusCodeValue()== 200 && !StringUtils.isEmpty(res.getBody())){
String xmlStr = res.getBody().toString();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType("UTF-8");
HttpEntity<String> requestEntity = new HttpEntity<String>(json, requestHeaders);
ResponseEntity<String> res = restTemplate.postForEntity(url, requestEntity , String.class);
String temp2 = null;
if(res.getStatusCodeValue()== 200 && !StringUtils.isEmpty(res.getBody())){
String xmlStr = res.getBody().toString();
// 将xml转为json
JSONObject xmlJSONObj = XML.toJSONObject(xmlStr);
// 设置缩进
String jsonPrettyPrintString = xmlJSONObj.toString(4);
JSONObject xmlJSONObj = XML.toJSONObject(xmlStr);
// 设置缩进
String jsonPrettyPrintString = xmlJSONObj.toString(4);
JSONObject temp = JSON.parseObject(jsonPrettyPrintString);
//取key=ResultUtil的值
temp2 = JsonProcess.returnValue(temp, "ResultUtil");
}
return temp2;
}
//取key=ResultUtil的值
temp2 = JsonProcess.returnValue(temp, "ResultUtil");
}
return temp2;
}
(2)不带header
以上是关于RestTemplate的用法总结的主要内容,如果未能解决你的问题,请参考以下文章
Spring Resttemplate:使用@JsonIgnore 解析导致值为空
Spring RestTemplate用法 Post Get Cookie