RestTemplate 发送get、put、post 请求
private JSONObject sendGet(String url, JSONObject param) {
JSONObject jsonObject = null;
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity httpEntity = new HttpEntity<>(param, headers);
ResponseEntity<String> resEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
jsonObject = JSON.parseObject(resEntity.getBody());
} catch (Exception e) {
if (e.toString().contains("timed out")) {
throw new ThirdException(EnumThirdCode.E_CONTRACT, "调用超时,请重试");
}
throw new ThirdException(EnumThirdCode.E_CONTRACT, "接口异常");
}
return jsonObject;
}
private JSONObject sendPut(String url, JSONObject param) {
JSONObject jsonObject = null;
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity httpEntity = new HttpEntity<>(param, headers);
ResponseEntity<String> resEntity = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class);
jsonObject = JSON.parseObject(resEntity.getBody());
} catch (Exception e) {
if (e.toString().contains("timed out")) {
throw new ThirdException(EnumThirdCode.E_CONTRACT, "调用超时,请重试");
}
throw new ThirdException(EnumThirdCode.E_CONTRACT, "接口异常");
}
return jsonObject;
}
private JSONObject sendPost(String url, JSONObject param) {
JSONObject jsonObject = null;
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity httpEntity = new HttpEntity<>(param, headers);
jsonObject = restTemplate.postForObject(url, httpEntity, JSONObject.class);
} catch (Exception e) {
if (e.toString().contains("timed out")) {
throw new ThirdException(EnumThirdCode.E_CONTRACT, "调用超时,请重试");
}
throw new ThirdException(EnumThirdCode.E_CONTRACT, "接口异常");
}
return jsonObject;
}