RestTemplate发送get,post请求
程序员文章站
2022-06-25 19:21:10
...
平时工作中有对接外部接口的需求,这边将自己用的做一个总结,大概用了四种
1.发送get请求返回对象
/**
* Result返回的是接口返回的格式公共响应对象
*/
private <T> Result<T> getForObject(String url, Class<T> clazz) {
try {
ResponseEntity<String> response = getStringResponseEntity(url);
if (response.getStatusCode().is2xxSuccessful()) {
return parseObjectResult(response.getBody(), clazz);
}
} catch (Exception e) {
log.error("调用出错,异常:{}", ExceptionUtils.getStackTrace(e));
}
// 失败的请求
Result<T> result = new Result<>();
result.setErrorCode("9998");
result.setErrorMsg("访问接口失败,请稍后重试!");
result.setSuccess(false);
return result;
}
2.发送get请求返回List对象
private <T> Result<List<T>> getForList(String url, Class<T> clazz) {
try {
ResponseEntity<String> response = getStringResponseEntity(url);
if (response.getStatusCode().is2xxSuccessful()) {
return parseListResult(response.getBody(), clazz);
}
} catch (Exception e) {
log.error("[xx]调用出错,异常:{}", ExceptionUtils.getStackTrace(e));
}
// 失败的请求
Result<List<T>> result = new Result<>();
result.setErrorCode("9998");
result.setErrorMsg("访问失败,请稍后重试!");
result.setSuccess(false);
return result ;
}
发送get请求公用的方法
private ResponseEntity<String> getStringResponseEntity(String url) {
log.debug("[xx]请求:url:{}, requestString:{}", url);
String accessToken = xxxService.getToken();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add(HttpHeaders.ACCEPT, MediaType.ALL_VALUE);
//在请求头里添加token
headers.add("Token", accessToken);
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
ResponseEntity<String> response = restTemplate
.exchange(url, HttpMethod.GET, new HttpEntity<String>(headers), String.class);
log.debug("[xx]结果:{}", response.getBody());
return response;
}
private <T> Result<List<T>> parseListResult(String body, Class<T> clazz) {
return JSONObject.parseObject(body, new TypeReference<Result<List<T>>>(clazz) {
});
}
private <T> Result<T> parseObjectResult(String body, Class<T> clazz) {
return JSONObject.parseObject(body, new TypeReference<Result<T>>(clazz) {
});
}
3.发送post请求返回对象
4.发送post请求返回List对象