Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA Using IOUtils.toString with HttpEntity.getContent() converting the InputStream to null

I have strange senario i have HTTP response which i try to convert to string , the problem is that the first time it is working but in the second time the InputStream data is null
and i have data only in response1

InputStream  is = entity.getContent();  
String response1 = IOUtils.toString(is, "utf-8");  // Here every thing is fine 
String respons2 = IOUtils.toString(is, "utf-8");   // Here the response2 is empty 
and is (InputStream) holding no data  

what is wrong here i need to be able to hold the data in the InputStream for future use in the code

like image 496
user63898 Avatar asked Jul 27 '26 20:07

user63898


1 Answers

Your need is not very clear however, when checking the javadoc httpEntity.getContent I see the following:

Returns a content stream of the entity. Repeatable entities are expected to create a new instance of InputStream for each invocation of this method and therefore can be consumed multiple times. Entities that are not repeatable are expected to return the same InputStream instance and therefore may not be consumed more than once.

Did you check that the httpEntity is repeatable by calling

httpEntity.isRepeatable()

if true, you could do the following:

InputStream  is = entity.getContent();  
String response1 = IOUtils.toString(is, "utf-8");

// retrieve a new instance of inputStream
is = entity.getContent();
String response2 = IOUtils.toString(is, "utf-8");    

Last but not least (since I do not know your exact need), the previous code will helps if the entity is capable of producing its data more than once but nevertheless you should evaluate the cost between:

  • consuming the data once and keep it in string
  • consuming the data several times
like image 172
VirtualTroll Avatar answered Jul 29 '26 10:07

VirtualTroll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!