【问题标题】:How To Consume Stream HTTP Response In Java?如何在 Java 中使用流 HTTP 响应?
【发布时间】:2020-04-17 17:43:04
【问题描述】:

我在尝试使用持续流式传输实时事件的 HTTP 端点的响应时遇到问题。它实际上是 Docker 的端点之一:https://docs.docker.com/engine/api/v1.40/#operation/SystemEvents

我使用的是 Apache HTTP Client 4.5.5,当我尝试使用 InputStream 内容时它会无限期停止:

HttpEntity entity = resp.getEntity();
EntityUtils.consume(entity);//it just hangs here.
//Even if I don't call this method, Apache calls it automatically
//after running all my ResponseHandlers

显然,可以通过使用JDK的原始URLStream a HTTP response in Java来完成

但我不能这样做,因为本地 Docker 通过 Unix 套接字进行通信,我只设法在 Apache 的 HTTP 客户端中使用 Java 中的 Unix 套接字的第 3 方库进行配置。

如果我可以切换到更智能的 HTTP 客户端库,那也是一个选择。

任何想法将不胜感激。谢谢!

【问题讨论】:

    标签: docker http java-8 stream apache-httpclient-4.x


    【解决方案1】:

    我设法通过从响应 InputStream 生成无限 java.util.stream.StreamJsonObject 来解决这个问题(我知道 json 读取部分不是最优雅的解决方案,但该 API 没有更好的方法,还有 Docker不会在 json 之间发送任何分隔符)。

    final InputStream content = response.getEntity().getContent();
    final Stream<JsonObject> stream = Stream.generate(
        () -> {
            JsonObject read = null;
            try {
                final byte[] tmp = new byte[4096];
                while (content.read(tmp) != -1) {
                    try {
                        final JsonReader reader = Json.createReader(
                            new ByteArrayInputStream(tmp)
                        );
                        read = reader.readObject();
                        break;
                    } catch (final Exception exception) {
                        //Couldn't parse byte[] to Json,
                        //try to read more bytes.
                    }
                }
            } catch (final IOException ex) {
                throw new IllegalStateException(
                    "IOException when reading streamed JsonObjects!"
                );
            }
            return read;
        }
    ).onClose(
        () -> {
            try {
                 ((CloseableHttpResponse) response).close();
            } catch (final IOException ex) {
                //There is a bug in Apache HTTPClient, when closing
                //an infinite InputStream: IOException is thrown
                //because the client still tries to read the remainder
                // of the closed Stream. We should ignore this case.
            }
        }
    );
    return stream;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-17
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      • 2013-11-04
      • 2013-08-20
      • 1970-01-01
      相关资源
      最近更新 更多