Eduardo
Eduardo

Reputation: 21058

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.

Upvotes: 7

Views: 4008

Answers (3)

RaceBase
RaceBase

Reputation: 18848

Try to Use Apache Utilities. In my preset project, I have done the same thing

InputStream xml = connection.getInputStream();

String responseData = IOUtils.toString(xml);

You can get IOUtils from Apache [import org.apache.commons.io.IOUtils]

Upvotes: 0

mhshams
mhshams

Reputation: 16962

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

Upvotes: 10

Antony
Antony

Reputation: 85

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.

Upvotes: 2

Related Questions