javaapache-httpcomponentshttpentity

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 e.g.

Sample Code:

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

Any hint appreciated.


Solution

  • 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:

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