Spring WebFlux WebClient:接收部分响应

时间:2018-06-19 20:15:05

标签: java webclient spring-webflux

我使用WebClient(spring webflux)发送一些信息,并且并不真正在乎响应,只记录它即可。如果它很大,我不需要读取所有内容,而只需读取500个字节左右。据我了解,bodyToMono()将整个身体读入内存。如何获得一个身体的开始?

         for line, entry in enumerate(worksheet, start=1):
                #logging.info('working on row: %s' % (row))
                for cell in entry:
                    #try:
                    xy = openpyxl.utils.coordinate_from_string(cell.coordinate) # returns ('A',4)
                    col = openpyxl.utils.column_index_from_string(xy[0]) # returns 1
                    rowCord = xy[1]
                    # add cell value to output file
                    #currentSheet[cell.coordinate].value
                    if line == 1 and inputFileCount == 1:
                        currentSheet.cell(row=1, column=1).value = 'Project'
                        currentSheet.cell(row=1, column=2).value = os.path.split(inputFile)[-1]
                    if line == 1 and inputFileCount > 1:
                        currentSheet.cell(row=outputSheetMaxRow + 2, column=1).value = 'Project'
                        currentSheet.cell(row=outputSheetMaxRow + 2, column=2).value = os.path.split(inputFile)[-1]
                    else:
                        currentSheet.cell(row=outputSheetMaxRow + rowCord + 1, column=col).value = cell.value #, value=cell

1 个答案:

答案 0 :(得分: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个字符。