Shravan
Shravan

Reputation: 341

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.

Upvotes: 3

Views: 2886

Answers (2)

Nicolas Buquet
Nicolas Buquet

Reputation: 3955

You must limit buffering by specifying the streaming mode either by giving the final length of the uploaded information via setFixedLengthStreamingMode method, or setting mode to streaming if final length is not known via setChunkedStreamingMode method:

    // For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance,
    // or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory
    // before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.
    //
    // see: https://developer.android.com/reference/java/net/HttpURLConnection.html

    _connection.setChunkedStreamingMode(1024);

If you don't, the real transfer will occur when you call getInputStream().

See https://developer.android.com/reference/java/net/HttpURLConnection.html

Upvotes: 1

user207421
user207421

Reputation: 310859

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.

Upvotes: 1

Related Questions