springboot接口调用flask
时间: 2023-12-06 13:38:10 浏览: 97
为了在Spring Boot应用程序中调用Flask API,我们可以使用Java的RestTemplate类。RestTemplate是Spring框架中的一个HTTP客户端,它可以用于发送HTTP请求并处理响应。下面是一个简单的示例,演示如何使用RestTemplate从Spring Boot应用程序调用Flask API:
```java
import org.springframework.web.client.RestTemplate;
@RestController
public class MyController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/callFlaskAPI")
public String callFlaskAPI() {
String url = "http://localhost:5000/myAPI";
String response = restTemplate.getForObject(url, String.class);
return response;
}
}
```
在上面的代码中,我们使用RestTemplate类的getForObject()方法发送GET请求并获取响应。我们将Flask API的URL传递给getForObject()方法,并指定响应的类型为String。
需要注意的是,我们需要在Spring Boot应用程序中添加RestTemplate类的依赖项。可以在pom.xml文件中添加以下依赖项:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
```