在独立应用程序中使用Spring WebClient

时间:2018-09-23 16:22:43

标签: spring-boot spring-webflux

我有一个独立的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);

    } 

谢谢。

1 个答案:

答案 0 :(得分:1)

您做错了...应该是这样的:

WebClient webClient = WebClient.create("http://localhost:8080");
Mono<String> result = webClient.get()
   .retrieve()
   .bodyToMono(String.class);
String response = result.block();
System.out.println(response);
相关问题