This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

分块读写

HttpClient支持分块写请求数据及分块处理响应数据,分块读功能请参考自定义响应处理,此处不再赘述。本文仅介绍分块写请求body相关功能。

使用方式

final HttpClient client = HttpClient.ofDefault();

final SegmentRequest request = client.post("http://127.0.0.1:8080/").segment();

for (int i = 0; i < 100; i++) {
    // request.isWritable()判断适用于较大内容的分块写
    if (request.isWritable()) {
        request.write("It's body".getBytes());
    } else {
        throw new IllegalStateException("Channel is unwritable");
    }
}

HttpResponse response = request.end("It's end".getBytes()).get();
System.out.println(response.status());
System.out.println(response.body().string(StandardCharsets.UTF_8));

如上所示,使用时通过HttpClient构造一个可分块写的SegmentRequest并在有可写数据时直接写入,最后结束请求。