首页 文章

Spring WebFlux WebClient:接收部分响应

提问于
浏览
1

我使用WebClient(spring webflux)发送一些信息,并不关心响应,只需记录它 . 如果它很大,我不需要读取所有内容,但只需要500字节左右 . 据我所知bodyToMono()将整个身体读入记忆中 . 如何只获得一个身体的开始?

client.post()
   .syncBody(payload)
   .retrieve()
   .bodyToMono(String.class)
   .subscribe( r -> logResponce(r),
               t -> logException(t));

1 回答

  • 2

    这是我能够带来的最好的:

    WebClient client = WebClient.create("http://www.example.com/");
        client.post()
           .syncBody("test")
           .exchange()
           .flatMap(response->response.body((t,m)->t.getBody().next()))
           .subscribe( r -> {
                  System.out.println("Available bytes:" + r.readableByteCount());
                  final int limit = r.readableByteCount() < 500 ? r.readableByteCount() : 500;
                  System.out.println("Limit:" + limit);
                  byte[] dst = new byte[limit];
                  r.asByteBuffer().get(dst, 0, limit);
                  System.out.println("body=" + new String(dst, StandardCharsets.UTF_8));
              },
              t -> System.out.println(t));
    

    它消耗第一个数据块并打印前500个字符 .

相关问题