springboot调用flask接口
时间: 2023-10-09 21:06:28 浏览: 59
要在Spring Boot中调用Flask接口,你需要使用Spring的RestTemplate类发送HTTP请求。RestTemplate是Spring提供的用于处理HTTP请求的类,可以通过它发送GET、POST、PUT、DELETE等请求。
下面是一个简单的示例代码,演示如何使用RestTemplate调用Flask接口:
```
@RestController
public class MyController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/callFlaskApi")
public String callFlaskApi() {
String url = "http://localhost:5000/myFlaskApi";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return response.getBody();
}
}
```
在上面的代码中,我们注入了一个RestTemplate实例,并在@GetMapping注解的方法中使用它来发送GET请求。我们调用了Flask接口的URL是"http://localhost:5000/myFlaskApi",然后使用getForEntity方法发送请求并获取响应。
需要注意的是,如果你的Flask接口需要发送POST请求,那么你需要使用RestTemplate的postForEntity方法。同样,如果你的接口需要发送PUT或DELETE请求,你需要使用put和delete方法。
另外,你需要确保Flask服务正在运行,并且接口的URL是正确的。