首页 > 解决方案 > 在不消耗流的情况下保留 HTTPEntity

问题描述

我正在使用 org.apache.http.client.HttpClient 并且我正在尝试访问请求 HTTPEntity 的有效负载而不消耗底层流。我尝试使用

EntityUtils.toString(someEntity);

但这会消耗流。我只想保留在 HTTP 请求中发送到 String 对象的有效负载,例如

示例代码:

String uri = "someURI";
HttpPut updateRequest = new HttpPut(uri);         
updateRequest.setEntity(myHttpEntity);

任何提示表示赞赏。

标签: javaapache-httpcomponentshttpentity

解决方案


HttpEntity 必须是repeatable可重复使用的。该方法isRepeatable()显示是否是这种情况。

两个实体是可重复的:

  • 字符串实体
  • 字节数组实体

这意味着您必须将其中之一添加到原始请求中,以便您可以继续使用其内容。

public void doExample() {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPut httpPut = new HttpPut("some_url");
    httpPut.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
    StringEntity jsonEntityOrso = new StringEntity("{ \"hello\": \"some message\" }");
    httpPut.setEntity(jsonEntityOrso);
    StringEntity reusableEntity = (StringEntity) httpPut.getEntity();
    String hello = readInputStream(reusableEntity.getContent());
    String hello2 = readInputStream(reusableEntity.getContent());
    boolean verify = hello.equals(hello2); // returns true
}

private String readInputStream(InputStream stream) {
    return new BufferedReader(
        new InputStreamReader(stream, StandardCharsets.UTF_8))
        .lines()
        .collect(Collectors.joining("\n"));
}

推荐阅读