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

I used this question

How to convert InputStream to String in Java?

to convert InputStream to String using 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 input stream comes from an HttpURLConnection InputStream, and when I do my conversion to String, the input stream changes and I can no longer use it. This is the error I get:

 Premature end of file.' SOAP 

What can I do to save my input stream when I convert it to a string with relevant information?

In particular, this is information that changes:

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

Thanks.

+7
source share
3 answers

If you transfer your input stream to the scanner or read its data in any other way. you are actually consuming your data and there will be no more data available in this stream.

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

 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); 
+10
source

The scanner reads to the end of the stream and closes it. Thus, it will be unavailable. Use a PushbackInputStream as a wrapper for your input stream and use the unread() method.

+2
source

Try using Apache utilities. In my predefined project, I did the same

InputStream xml = connection.getInputStream ();

String responseData = IOUtils.toString (xml);

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

0
source

All Articles