RestTemplate 发送get、put、post 请求
程序员文章站
2022-06-25 20:27:08
...
RestTemplate 发送get、put、post 请求
/**
* 发送请求Get请求
*
* @param url 请求接口
* @param param 请求参数
*/
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;
}
/**
* 发送请求Put请求
*
* @param url 请求接口
* @param param 请求参数
*/
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;
}
/**
* 发送请求Post请求
*
* @param url 请求接口
* @param param 请求参数
*/
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;
}
上一篇: 怎么用Apple Music收听广播?
下一篇: 安装MySQL出现的问题
推荐阅读
-
IE6通过get发送奇数个汉字请求会乱码的解决方法_PHP教程
-
PHP模拟发送POST请求之三、加强file_get_contents发送POST请求
-
post请求重定向到get请求问题
-
php自定义类fsocket模拟post或get请求的方法_PHP
-
java发送http get请求的两种方式
-
java发送http get请求的两种方法(总结)
-
浅谈IOS中AFNetworking网络请求的get和post步骤
-
Python 使用requests模块发送GET和POST请求的实现代码
-
java网络编程中向指定URL发送GET POST请求示例
-
Python 使用requests模块发送GET和POST请求的实现代码