在spring引导应用程序中,从自己的rest api调用另一个rest api



我正在学习Spring Boot,我已经在我的计算机上部署了一个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();
}

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

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

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

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

您可以将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);

这个网站有一些使用spring的RestTemplate 的好例子

创建RestTemplate 的@Bean

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

通过使用上面的RestTemplate,您可以从自己的localhost 中获取数据

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

最新更新