zl程序教程

您现在的位置是:首页 >  后端

当前栏目

使用 RestTemplate 调用 restful 服务详解程序员

restful服务程序员 使用 详解 调用 RestTemplate
2023-06-13 09:20:05 时间

RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求,可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。
ClientHttpRequestFactory接口主要提供了两种实现方式

一种是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)创建底层的Http请求连接。 一种方式是使用HttpComponentsClientHttpRequestFactory方式,底层使用HttpClient访问远程的Http服务,使用HttpClient可以配置连接池和证书等信息。

RestTemplate默认是使用SimpleClientHttpRequestFactory,内部是调用jdk的HttpConnection,默认超时为-1

使用示例:
import org.springframework.beans.factory.annotation.Autowired; 

import org.springframework.boot.SpringApplication; 

import org.springframework.boot.autoconfigure.SpringBootApplication; 

import org.springframework.boot.web.client.RestTemplateBuilder; 

import org.springframework.context.annotation.Bean; 

import org.springframework.web.client.RestTemplate; 

@SpringBootApplication 

public class SpringbootRestTemplateApplication { 

 // 启动的时候要注意,由于我们在controller中注入了RestTemplate,所以启动的时候需要实例化该类的一个实例 

 @Autowired 

 private RestTemplateBuilder builder; 

 // 使用RestTemplateBuilder来实例化RestTemplate对象,spring默认已经注入了RestTemplateBuilder实例 

 @Bean 

 public RestTemplate restTemplate() { 

 return builder.build(); 

 public static void main(String[] args) { 

 SpringApplication.run(SpringbootRestTemplateApplication.class, args); 

}
编写controller
import org.springframework.beans.factory.annotation.Autowired; 

import org.springframework.web.bind.annotation.GetMapping; 

import org.springframework.web.bind.annotation.PathVariable; 

import org.springframework.web.bind.annotation.RestController; 

import org.springframework.web.client.RestTemplate; 

import com.chhliu.springboot.restful.vo.User; 

@RestController 

public class RestTemplateController { 

 @Autowired 

 private RestTemplate restTemplate; 

 @GetMapping("/template/{id}") 

 public User findById(@PathVariable Long id) { 

 //http://localhost:8080/user/ 是服务的对应的url 

 User u = this.restTemplate.getForObject("http://localhost:8080/user/" + id,User.class); 

 System.out.println(u); 

 return u; 

}