Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does HTTPURLConnection.getInputStream() takes time

I have a task to download & upload a file using HTTP protocol in Android (Java platform).

I am using following code for uploading a file:

HttpURLConnection httpURLConnection = (HttpURLConnection) serverUrl.openConnection();
....
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();

And Using following code for downloading a file:

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
...
urlConnection.connect();
DataInputStream stream = new DataInputStream(urlConnection.getInputStream());

As per my observation connect() for both the case takes time because it is communicating with network at this point. And for file upload, getOutputStream() gets execute very fast so does it means it is not communicating to network?

Whereas getInputStream() (in file download) takes some time (around 200 to 2500 mili sec) to execute. Does it mean it is communicating with network at this point? If yes then why so?

Experts, Please provide your comments on this & correct me if I am wrong anywhere.

like image 431
Shravan Avatar asked Feb 22 '26 05:02

Shravan


1 Answers

HTTP is a request/response protocol. You need a TCP connection. The connect() method creates that. Then you need to send a request. You call getOutputStream() for that, and you write it.

At this point nothing has been written to the network (in normal transfer mode), because the content-length header has to be set, and Java doesn't know when you've finished writing. So when you call getInputStream() (or getResponseCode()), Java sets the content-length header, writes the request, waits for the server to start generating a response, reads all the response headers, and then gives you an input stream positioned at the beginning of the body of the response. All those steps take time.

like image 61
user207421 Avatar answered Feb 23 '26 18:02

user207421



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!