RestTemplate框架的使用
2.1、关于RestTemplate
- RestTemplate是由Spring框架提供的一个可用于应用中调用rest服务的类它简化了与http服务的通信方式,统一了RESTFul的标准,封装了http连接,我们只需要传入url及其返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更为优雅的调用RESTFul服务的方式。
- 因为RestTemplate本身是spring框架提供的,所以不需要导入相关的依赖
2.2、RestTemplate的使用步骤
-
1、注册RestTemplate
可以自定义一些连接参数,如:连接超时时间,读取超时时间,还有认证信息等
@Configuration public class WebConfiguration { @Bean public RestTemplate restTemplate(RestTemplateBuilder builder){ return builder //设置连接超时时间 .setConnectTimeout(Duration.ofSeconds(5000)) //设置读取超时时间 .setReadTimeout(Duration.ofSeconds(5000)) //设置认证信息 .basicAuthentication("username","password") //设置根路径 .rootUri("https://api.test.com/") //构建 .build(); } } -
2、关于RestTemplate API的使用
这只是我个人的笔记,所以我不列举太多的的api, 我这里仅仅说明我使用的api
-
Get请求
- getForObject(String url, Class responseType, Map<String, ?> uriVariables)
- url - url
- responseType -返回值的类型
public void queryWeather() { Object body = restTemplate.getForObject("https://restapi.amap.com/v3/weather/weatherInfo?city=510100&key=e7a5fa943f706602033b6b329c49fbc6", Object.class); System.out.println(body); } - getForObject(String url, Class responseType, Map<String, ?> uriVariables)
-
POST请求
- public T postForObject(URI url, Object request, Class responseType) throws RestClientException
- url - url
- request——参数表示上传的参数(json格式提交),可以是空的
- responseType -返回值的类型
public void queryWeather() { User user = new User(); user.setName("鲁大师"); ResponseEntity<Object> objectResponseEntity = restTemplate.postForEntity("https://httpbin.org/post", user, Object.class); MediaType contentType = objectResponseEntity.getHeaders().getContentType(); System.out.println(contentType); System.out.println("消息响应内容:"+objectResponseEntity.getBody()); } - public T postForObject(URI url, Object request, Class responseType) throws RestClientException
-
RestTemplate是Spring提供的用于调用REST服务的工具,简化HTTP通信,支持设置超时和认证信息。示例中展示了如何注册RestTemplate以及使用它进行GET和POST请求,包括查询天气信息和发送JSON数据。
3640

被折叠的 条评论
为什么被折叠?



