【问题标题】:No data received from endpoint when using Spring WebClient but I can use curl to fetch the data使用 Spring WebClient 时没有从端点接收到数据,但我可以使用 curl 来获取数据
【发布时间】:2019-05-23 09:44:06
【问题描述】:

我有一个发送服务器端事件的端点。出于测试目的,我使端点具有确定性,并且与端点的连接在 30 秒后终止。如果我卷曲端点,我会按预期获得所有数据:

$ curl "my/end/point"
data: {"message": "event1"}

data: {"message": "event2"}

data: {"message": "event3"}

data: {"message": "event4"}

...

但是,当我使用 Springs WebClient 时,没有收到任何数据。我使用的代码:

final WebClient webClient = WebClient.create("my/end/point");
final String result = webClient.get()
                               .retrieve()
                               .bodyToFlux(String.class)
                               .blockFirst();
System.out.println(result);

当我运行这段代码时,我会在 30 秒后得到以下结果:

null

请求的响应代码是 200 OK。

下面的例子

final StringBuilder result = new StringBuilder();
final URL url = new URL("my/end/point");
final URLConnection conn = url.openConnection();
final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
    result.append(line);
}
rd.close();
System.out.println(result.toString());

运行 30 秒后显示预期结果

data: {"message": "event1"}

data: {"message": "event2"}

...

有谁知道为什么 WebClient 的结果是空的,而其他从端点获取数据的方法却不是?我正在使用 java 11 和 spring-webflux 版本 5.1.5。

【问题讨论】:

    标签: java reactive-programming spring-webflux spring-webclient


    【解决方案1】:

    我解决了这个问题,而不是做

    final WebClient webClient = WebClient.create("my/end/point");
    

    在做

    final WebClient webClient = WebClient.builder()
                                         .clientConnector(new ReactorClientHttpConnector(HttpClient.create()))
                                         .baseUrl(this.legalThingsSocketSettings.getUrl())
                                         .build();
    

    确实有效,尽管我有点困惑,因为ReactorClientHttpConnector 应该是WebClient 的默认客户端连接器。

    【讨论】:

      猜你喜欢
      • 2015-02-01
      • 1970-01-01
      • 2012-04-03
      • 2020-12-10
      • 2019-10-25
      • 2011-09-09
      • 2022-01-21
      • 2021-09-16
      • 1970-01-01
      相关资源
      最近更新 更多