【问题标题】:Call another rest api from own rest api in spring boot application在spring boot应用程序中从自己的rest api调用另一个rest api
【发布时间】:2020-07-17 06:28:42
【问题描述】:

我正在学习 Spring Boot,我设法在我的计算机上部署了一个从 Oracle 获取数据的 API,当我将链接 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();
    }

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

【问题讨论】:

  • 使用RestTemplate,我们可以从当前api调用外部rest api。

标签: java spring spring-boot rest api


【解决方案1】:

是的,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);
   }
}

您可以创建一个配置类来为其余控制器定义 Bean。下面是sn-p,

@Configuration
public class ApplicationConfig{

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

}

【讨论】:

  • 休息模板的不必要的自动装配。
  • 是的,这是一个显示 RestTemplate 的 sn-p。为了避免我们可以这样使用的自动装配,RestTemplate restTemplate = new RestTemplate()
【解决方案2】:

您可以使用RestTemplate 进行第三方API 调用并从您的API 返回响应

final String uri = "https://services.odata.org/V3/Northwind/Northwind.svc/Customers";

RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);

This website has some nice examples for using spring's RestTemplate

【讨论】:

  • 先生,您是对的,您的解决方案是最好的方法,但上述答案完全符合我在问题中提出的确切要求。您的答案以字符串形式返回给我地址,但所选答案还向我展示了如何重定向到该特定地址(这正是我所需要的)。希望你能理解:)顺便说一句,我也感谢你的帮助,先生
【解决方案3】:

创建一个@Bean 的 RestTemplate

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

通过使用上面的 RestTemplate 你可以从你自己的本地主机获取数据

  String url = "https://services.odata.org/V3/Northwind/Northwind.svc/Customers";
  restTemplate.getForObject(url,String.class);

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多