Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a copy of an InputStream from an HttpURLConnection so it can be used twice

I used this question

How do I convert an InputStream to a String in Java?

to convert an InputStream to a String with this code:

public static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
} 

My inputstream comes from an HttpURLConnection InputStream, and when I do my conversion to String, the inputstream changes and I cannot longer use it. This is the error that I get:

Premature end of file.' SOAP

What can I do to keep my inputstream, when I convert it to string with the proper information?.

Speciffically this is the information that changes:

inCache = true (before false)
keepAliveConnections = 4 (before 5)
keepingAlive = false (before true)
poster = null (before it was PosterOutputStream object with values)

Thank you.

like image 685
Eduardo Avatar asked Nov 08 '12 12:11

Eduardo


2 Answers

If you pass your input stream into scanner or read its data in any other way. you actually consuming its data and there will be no available data in that stream anymore.

you may need to create a new input stream with same data and use it instead of the original one. for example:

ByteArrayOutputStream into = new ByteArrayOutputStream();
byte[] buf = new byte[4096];

// inputStream is your original stream. 
for (int n; 0 < (n = inputStream.read(buf));) {
    into.write(buf, 0, n);
}
into.close();

byte[] data = into.toByteArray();

//This is your data in string format.
String stringData = new String(data, "UTF-8"); // Or whatever encoding  

//This is the new stream that you can pass it to other code and use its data.    
ByteArrayInputStream newStream = new ByteArrayInputStream(data);
like image 167
mhshams Avatar answered Oct 06 '22 00:10

mhshams


The scanner reads till the end of the stream and closes it. So it will not be available further. Use PushbackInputStream as a wrapper to your input stream and use the unread() method.

like image 29
Antony Avatar answered Oct 06 '22 00:10

Antony