简体   繁体   中英

Preserve a HTTPEntity without consuming the stream

I'm using org.apache.http.client.HttpClient and I'm trying to access the payload of the request HTTPEntity without consuming the underlying stream. I tried using

EntityUtils.toString(someEntity);

but this consumes the stream. I just want to preserve the payload which was sent in a HTTP request to a String object for eg

Sample Code:

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

Any hint appreciated.

A HttpEntity must be repeatable for it to be repeatedly consumable. The method isRepeatable() shows whether or not this is the case.

Two entities are repeatable:

  • StringEntity
  • ByteArrayEntity

This means you have to add one of these to the original request so you can keep using using its content.

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"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM