在Spring Boot应用程序中从自己的rest api调用另一个rest api

Mir*_*lal 3 java api rest spring spring-boot

我正在学习 Spring Boot,我已经设法在我的计算机上部署一个 API,该 API 从 Oracle 获取数据,当我在浏览器中粘贴链接http://localhost:8080/myapi/ver1/table1data时,它会返回数据。下面是我的控制器代码:

@CrossOrigin(origins = "http://localhost:8080")
@RestController
@RequestMapping("/myapi/ver1")
public class Table1Controller {


    @Autowired
    private ITable1Repository table1Repository;

    @GetMapping("/table1data")
    public List<Table1Entity> getAllTable1Data() {
        return table1Repository.findAll();
    }
Run Code Online (Sandbox Code Playgroud)

现在这个场景运行良好。我想做另一件事。有一个 API https://services.odata.org/V3/Northwind/Northwind.svc/Customers返回一些客户数据。Spring Boot 是否提供了任何方法,以便我可以从自己的控制器重新托管/重新部署此 API,这样我应该点击http://localhost:8080/myapi/ver1而不是在浏览器中点击上面的链接/table1data它会返回给我相同的客户数据。

Vig*_*T I 5

是的,Spring Boot 提供了一种通过 RestTemplate 从应用程序访问外部 URL 的方法。下面是获取字符串响应的示例实现,或者您也可以根据响应使用所需选择的数据结构,

@RestController
@RequestMapping("/myapi/ver1")
public class Table1Controller {

   @Autowired
   private RestTemplate restTemplate;

   @GetMapping("/table1data")
   public String getFromUrl() throws JsonProcessingException {
        return restTemplate.getForObject("https://services.odata.org/V3/Northwind/Northwind.svc/Customers",
            String.class);
   }
}
Run Code Online (Sandbox Code Playgroud)

您可以创建一个配置类来定义其余控制器的 Bean。下面是片段,

@Configuration
public class ApplicationConfig{

   @Bean
   public RestTemplate restTemplate() {
       return new RestTemplate();
   }

}
Run Code Online (Sandbox Code Playgroud)