user1841702
user1841702

Reputation: 2763

Does URLConnection's getInputStream() return the same InputStream every time?

It is very common to get an InputStream from URLConnection like so:

InputStream stream =  connection.getInputStream();

where connection is a URLConnection.

https://developer.android.com/reference/java/net/URLConnection.html#getInputStream()

I have a situation where I would like to reuse a stream. I have access to the connection object and my question now is does a single instance of a URLConnection return the 'same' InputStream every time ? That is if I call connection.getInputStream() again (but for the same connection object) will I be getting a new stream ?

Upvotes: 1

Views: 1070

Answers (3)

user207421
user207421

Reputation: 310883

It doesn't matter. It wouldn't make any difference whether it did or it didn't. Consider a method that always returns new DataInputStream(socket.getInputStream()). (I don't claim it is implemented like that: we are just considering.) There is nothing practical you can do with the stream short of comparing it with == that would tell you whether it was a new stream each time like that or always the same stream. What you read out of it is not affected.

Upvotes: 0

Pradhan
Pradhan

Reputation: 508

URLConnection is an interface and it all depends on the implementors if the getInputStream returns a new stream or not.

The best way to verify this is...

URLConnection con = new URL(MY_URL_STRING).openConnection() ;
InputStream in1 = con.getInputStream(); 
InputStream in2 = con.getInputStream();
boolean streamEquals = in1.equals(in2);

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074238

In general, the answer to this kind of question ("Does X do Y?") is: Does the documentation say X does Y? If so, yes (or it's broken); if not, you have no guarantee so and must assume not.

So let's look at URLConnection#getInputStream's documentation:

Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.

Returns:

an input stream that reads from this open connection.

So you can't rely on it doing so, because it doesn't promise to. (I also looked elsewhere in the JavaDoc for URLConnection.)

(My tests outside Android suggest that HttpURLConnection does at least sometimes, though.)

Upvotes: 2

Related Questions