使用RestTemplate发送post和delete请求

时间:2022-02-03 21:10:45

使用RestTemplate发送post和delete请求,其中delete请求需要特别支持eg:

RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
@Override
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
if (HttpMethod.DELETE == httpMethod) {
return new HttpEntityEnclosingDeleteRequest(uri);
}
return super.createHttpUriRequest(httpMethod, uri);
}
});

HttpHeaders headers = new HttpHeaders();
MediaType type2 = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type2);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());

JSONObject jsonObj = new JSONObject();
value = DigestUtils.sha1Hex(DigestUtils.sha1Hex(value));

jsonObj.put("field", field2);
jsonObj.put("value", value);
jsonObj.put("reportTime", (new Date()).getTime());
jsonObj.put("type", "OFFLINE");

HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
JSONObject res = new JSONObject();
if(REPORT_ADD.equals(type)){
res = restTemplate.postForObject(url, formEntity, JSONObject.class);
}else if(REPORT_DELETE.equals(type)){
ResponseEntity<JSONObject> exchange = restTemplate.exchange(url, HttpMethod.DELETE, formEntity, JSONObject.class);
res = exchange.getBody();
}

if(res.get("status_code") != null && STATE_CODE_SUCESS.equals(res.get("status_code").toString().trim())){
}else{
if(res.get("status_code") == null){
msg = "未获取到返回状态码!";
}else if(STATE_CODE_ERROR.equals(res.get("status_code").toString().trim())){
msg = "系统错误!";
}else if(STATE_CODE_INVALID.equals(res.get("status_code").toString().trim())){
msg = "该接口未授权!";
}else if(STATE_CODE_NO_MATCH.equals(res.get("status_code").toString().trim())){
msg = "未匹配到(未查找到对应项)!";
}else if(STATE_CODE_REQUEST_FORMAT_ERROR.equals(res.get("status_code").toString().trim())){
msg = "请求参数格式校验失败!";
}
}
return msg;