Spring RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,RestTemplate 提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率
调用 RestTemplate 的默认构造函数,RestTemplate 对象在底层通过使用 java.net 包下的实现创建 HTTP 请求,可以通过使用 ClientHttpRequestFactory 指定不同的HTTP请求方式。默认使用 SimpleClientHttpRequestFactory,是 ClientHttpRequestFactory 实现类。
RestTemplate能大幅简化了提交表单数据的难度,并且附带了自动转换JSON数据的功能
使用RestTemplate 访问请求非常的简单粗暴无脑。例如:
RestTemplate restTemplate = new RestTemplate();
ResponseBean responseBean = restTemplate.postForObject(url, requestBean, ResponseBean.class);
(
url, requestBean, ResponseBean.class)
这三个参数分别代表:请求地址、请求参数、HTTP响应被转换成的对象类型。
requestBean 请求参数可以为空,ResponseBean 为返回值类型。
示例:
import org.springframework.web.client.RestTemplate;
/**
* 不带参数的请求示例
* get 请求
*/
// http 请求url,返回ReturnResult类型数据
public ReturnResult request(String url) {
RestTemplate restTemplate = new RestTemplate();
ReturnResult result = restTemplate.getForObject(url, ReturnResult.class);
return result;
}
/**
* 带参数的请求示例
* post 请求
* 该示例你请求的接口:请求参数类型为json,返回类型为json
*/
public static void main(String[] args) {
String url = "http://127.0.0.1:8888/app/getCustInfo?token=d3eb9a9233e52948740d7ab8c3062d14";
JSONObject json = new JSONObject();
json.put("beginDate", "2021-01-17");
json.put("endDate", "2021-06-22");
json.put("custOutCode", "");
json.put("pageNo", 1);
json.put("pageSize", 5);
RestTemplate restTemplate = new RestTemplate();
JSONObject responseBean = restTemplate.postForObject(url, json, JSONObject.class);
System.out.println(responseBean);
}
补充:
感谢博客:SpringBoot ——— 使用RestTemplate发送带token的GET和POST请求_自傷無色丶的博客-CSDN博客_resttemplate设置token
带 Token 的Get请求示例:
Post 请求示例:
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
public Result testPost(PostEntity postEntity,String token) {
MediaType type = MediaType.parseMediaType("application/json");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(type);
headers.add("Accept", MediaType.ALL_VALUE);
headers.add("Authorization", token);
JSONObject param = JSONUtil.parseObj(postEntity);
HttpEntity<String> formEntity = new HttpEntity<String>(param.toString(), headers);
ResponseEntity<Integer> responsebody = restTemplate.exchange(
saveLeaseContractUrl,
HttpMethod.POST,
formEntity,
Integer.class);
Integer contractId = responsebody.getBody();
}
带Headers 的请求示例:jsons 为请求参数(json格式)
private CisResult httpSgpRequest(String url, JSONObject jsons) {
log.info("向sgp请求的url为:{},参数为:{}", url, jsons);
HttpHeaders headers = new HttpHeaders();
headers.add("Accesskey", "d3eb9a9233e52948740d7eb8c3062d14");
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> requestEntity = new HttpEntity<>(jsons.toString(), headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
String.class
);
JSONObject res = JSONObject.parseObject(responseEntity.getBody(), JSONObject.class);
log.info("请求结果:{}", res);
if (res != null) {
if ("00".equals(res.get("resultCode"))) {
return CisResult.defaultOk();
}
return CisResult.defaultCheckError(res.getString("resultMsg"));
}
return CisResult.defaultError();
}
补充示例:Java后台请求第三方系统接口
public static String sendPost(String strUrl, String param, String token) {
log.info("发送参数:" + param);
StringBuilder result = new StringBuilder();
try {
// 创建连接
URL url = new URL(strUrl);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置post提交形式
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("authorization", "Bearer " + token);
connection.connect();
// POST请求
OutputStreamWriter oWriter = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
BufferedWriter out = new BufferedWriter(oWriter);
out.write(param);
out.flush();
oWriter.close();
out.close();
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String lines;
while ((lines = reader.readLine()) != null) {
result.append(lines);
}
log.info("响应:" + result);
reader.close();
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
log.error("请求接口错误,检查地址或参数是否正确");
log.error("异常原因", e);
result = new StringBuilder();
} catch (IOException e) {
log.error("写入数据异常:", e);
result = new StringBuilder();
}
return result.toString();
}