0

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.

Francesco Iannazzo
  • 596
  • 2
  • 11
  • 31

1 Answers1

1

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"));
}
TimonNetherlands
  • 1,033
  • 1
  • 6
  • 6
  • I will check that. I'm using StringEntity already but, when I try to use EntityUtils.toString twice. I get IOException: "Stream is closed ..." . But I will verify if I'm using everywhere String Entities. Merry Christma by the way. – Francesco Iannazzo Dec 24 '20 at 08:28
  • Merry Christmas. You're right by the way. It seems the EntityUtils poses a problem by closing the stream after getting the content. I've changed my answer to read the String directly from the Entity instead. – TimonNetherlands Dec 24 '20 at 09:11
  • Worked for me. Just had to change from StringEntity to HTTPEntity, because of class cast exception. – Francesco Iannazzo Jan 15 '21 at 10:34