1, restTemplate调用http ,post方法
@Value("{portrait.url}")
private String apiHost;
/**
* restTemplate调用http ,post方法
*
* @param
* @return
*/
@PostMapping("/api/item")
public Object post(@Valid @RequestBody ItemsPublishDTO itemsListDTO) {
//url ,apiHost路径写在配置类中
String url = apiHost+ "/item";
//请求头
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//携带请求头参数
headers.add("X-API-Key", "XX");
//参数
ItemsListDTO itemsListDTO = new ItemsListDTO();
itemsListDTO.setxxx();
itemsListDTO.setxxx();
net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(itemsPublishDTO);
HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
Object objectResponseEntity = restTemplate.postForObject(url ,formEntity ,Object.class);
logger.info("消息响应内容:"+objectResponseEntity);
return objectResponseEntity;
}
2, restTemplate调用http ,get方法
/**
* restTemplate调用http ,get方法
*
* @param
* @return
*/
@GetMapping("/api/item/{userId}")
public Object get(@PathVariable userId) {
//url
String url = "http://xxxx.com/api/item/"+userId ;
//请求头
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//携带请求头参数
headers.add("X-API-Key", "xxxx");
HttpEntity<JSONArray> formEntity = new HttpEntity<JSONArray>( headers);
Object objectResponseEntity = restTemplate.exchange(url ,HttpMethod.GET ,formEntity, Object.class).getBody();
logger.info("消息响应内容:"+objectResponseEntity);
List<String> result = new ArrayList<>();
return objectResponseEntity;
}
3, restTemplate调用http ,DELETE方法
/**
* restTemplate调用http ,DELETE方法
*
* @param
* @return
*/
@GetMapping("/api/item/{userId}")
public Object DELETE(@PathVariable userId) {
//url
String url = apiHost + "/user/" + id ;
//请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//携带请求头参数
headers.add("X-API-Key", "xxxx");
HttpEntity<String> formEntity = new HttpEntity<>(headers);
ResponseEntity<String> objectResponseEntity = restTemplate.exchange(url, HttpMethod.DELETE, formEntity, String.class);
logger.info("消息响应内容:"+objectResponseEntity);
return objectResponseEntity;
}