springboot如何调用restful接口
要调用RESTful接口,可使用Spring Boot的内置RestTemplate还是使用Feign客户端。
使用RestTemplate:
@Bean注解创建一个RestTemplate bean。@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}@Autowired
private RestTemplate restTemplate;getForObject()、postForObject()等方法调用RESTful接口。String url = "http://example.com/api/endpoint";
ResponseEntity response = restTemplate.getForObject(url, String.class); 使用Feign客户端:
@EnableFeignClients注解启用Feign客户端。@EnableFeignClients
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}@FeignClient注解指定要调用的服务名称和URL。@FeignClient(name = "example-service", url = "http://example.com/api")
public interface ExampleClient {
@GetMapping("/endpoint")
String getEndpoint();
}@Autowired
private ExampleClient exampleClient;String response = exampleClient.getEndpoint();以上是两种常见的在Spring Boot中调用RESTful接口的方法。根据实际情况选择适合的方式。
TOP