public JSONObject post(String url, Map<String, Object> params) throws RestClientException {
HttpEntity<?> httpEntity = getHttpEntity(params);
String body = JSONObject.toJSONString(httpEntity.getBody());
SysServiceLog sysServiceLog = SysServiceLog.builder().startTime(new Date()).serviceUrl(url).params(body).build();
log.info("url " + url);
log.info("body " + body);
restTemplate.setErrorHandler(new ResponseErrorHandler(){
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
// 返回false表示不管response的status是多少都返回没有错
// 这里可以自己定义那些status code你认为是可以抛Error
log.info("调用第三方返回的状态码为 : " + response.getRawStatusCode());
return false;
}
@Override
public void handleError(ClientHttpResponse response) {
// 这里面可以实现你自己遇到了Error进行合理的处理
}
});
ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
JSONObject responseBody = response.getBody();
if(responseBody != null){
sysServiceLog.setResults(responseBody.toJSONString());
}
log.info("results " + sysServiceLog.getResults());
sysServiceLog.setStatus(String.valueOf(response.getStatusCode().value()));
// 无论接口调用结果如何,都先插入日志。
if(!url.contains("list") & !url.contains("query") & !url.contains("get")){
AsyncManager.getInstance().execute(AsyncFactory.insertServiceLog(sysServiceLog));
}
if (response.getBody() == null) {
throw new ApplicationException("Response body is null");
}
return responseBody;
}
private HttpEntity<?> getHttpEntity(Map<String, Object> params) {
if (params == null) {
params = new HashMap<>(1);
}
params.put("timestamp", System.currentTimeMillis());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> httpEntity = new HttpEntity<>(params, headers);
return httpEntity;
}
调用第三方接口的工具类post方式
最新推荐文章于 2024-05-16 17:36:27 发布