在独立应用程序中使用 Spring WebClient
Using Spring WebClient in standalone application
我有一个独立的 spring-boot 应用程序,想使用 Spring 的 WebClient
来发出请求。但不知何故,WebClient
没有发出请求。不过,我可以使用 RestTemaplate
提出请求。我是不是遗漏了什么,或者 WebClient
不能在独立项目中使用?
@Test
public void test() {
final RestTemplate restTemplate = new RestTemplate();
// Able to make requests in standalone spring boot project using RestTemplate
restTemplate.getForEntity("http://localhost:8080/user", User.class)
.getBody();
// NOT Able to make requests in standalone spring boot project using WebClient
WebClient.create("http://localhost:8080/user")
.get()
.retrieve()
.bodyToMono(User.class);
}
提前致谢。
你做错了……应该是这样的:
WebClient webClient = WebClient.create("http://localhost:8080");
Mono<String> result = webClient.get()
.retrieve()
.bodyToMono(String.class);
String response = result.block();
System.out.println(response);
我有一个独立的 spring-boot 应用程序,想使用 Spring 的 WebClient
来发出请求。但不知何故,WebClient
没有发出请求。不过,我可以使用 RestTemaplate
提出请求。我是不是遗漏了什么,或者 WebClient
不能在独立项目中使用?
@Test
public void test() {
final RestTemplate restTemplate = new RestTemplate();
// Able to make requests in standalone spring boot project using RestTemplate
restTemplate.getForEntity("http://localhost:8080/user", User.class)
.getBody();
// NOT Able to make requests in standalone spring boot project using WebClient
WebClient.create("http://localhost:8080/user")
.get()
.retrieve()
.bodyToMono(User.class);
}
提前致谢。
你做错了……应该是这样的:
WebClient webClient = WebClient.create("http://localhost:8080");
Mono<String> result = webClient.get()
.retrieve()
.bodyToMono(String.class);
String response = result.block();
System.out.println(response);