SpringBoot整合RestTemplate与使用方法
1. 使用方法
1.1. 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1.2. 创建配置类
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
factory.setReadTimeout(5000);
return factory;
}
}
1.3. 在Bean中注入
@Service
public class demoService {
@Autowired
private RestTemplate restTemplate;
public String get(Integer id){
return restTemplate.getForObject("http://localhost:8080/user?userId=id",String.class);
}
}
2. API说明
RestTemplate定义了36个与REST资源交互的方法,其中的大多数都对应于HTTP的方法。
其实,这里面只有11个独立的方法,其中有十个有三种重载形式,而第十一个则重载了六次,这样一共形成了36个方法。
2.1. 总览
方法 | 描述 |
---|---|
delete() |
在特定的URL上对资源执行HTTP DELETE操作 |
exchange() |
在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity ,这个对象是从响应体中映射得到的 |
execute() |
在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象 |
getForEntity() |
发送一个HTTP GET请求,返回的ResponseEntity 包含了响应体所映射成的对象 |
getForObject() |
发送一个HTTP GET请求,返回的请求体将映射为一个对象 |
postForEntity() |
POST数据到一个URL,返回包含一个对象的ResponseEntity ,这个对象是从响应体中映射得到的 |
postForObject() |
POST数据到一个URL,返回根据响应体匹配形成的对象 |
headForHeaders() |
发送HTTP HEAD请求,返回包含特定资源URL的HTTP头 |
optionsForAllow() |
发送HTTP OPTIONS请求,返回对特定URL的Allow 头信息 |
postForLocation() |
POST数据到一个URL,返回新创建资源的URL |
put() |
PUT资源到特定的URL |
2.2. getForEntity
get请求就和正常在浏览器url上发送请求一样
下面是有参数的get请求
@GetMapping("getForEntity/{id}")
public User getById(@PathVariable(name = "id") String id) {
ResponseEntity<User> response = restTemplate.getForEntity("http://localhost/get/{id}", User.class, id);
User user = response.getBody();
return user;
}
2.3. getForObject
getForObject
和getForEntity
用法几乎相同,只是返回值返回的是响应体,省去了我们 再去getBody()
@GetMapping("getForObject/{id}")
public User getById(@PathVariable(name = "id") String id) {
User user = restTemplate.getForObject("http://localhost/get/{id}", User.class, id);
return user;
}
2.4. postForEntity
@RequestMapping("saveUser")
public String save(User user) {
ResponseEntity<String> response = restTemplate.postForEntity("http://localhost/save", user, String.class);
String body = response.getBody();
return body;
}
2.5. postForObject
用法与getForObject
一样
2.6. exchange
@PostMapping("demo")
public void demo(Integer id, String name){
HttpHeaders headers = new HttpHeaders();//header参数
headers.add("authorization",Auth);
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject obj = new JSONObject();//放入body中的json参数
obj.put("userId", id);
obj.put("name", name);
HttpEntity<JSONObject> request = new HttpEntity<>(content,headers); //组装
ResponseEntity<String> response = template.exchange("http://localhost:8080/demo",HttpMethod.POST,request,String.class);
}
转自:https://blog.csdn.net/weixin_40461281/article/details/83540604