jul
jul

Reputation: 37464

How to manage connection lost with HttpURLConnection?

I have a Service that manages downloading tasks using using HttpURLConnection.

I use a custom isNetworkAvailable method before performing any HTTP request, but I'm wondering how to manage connection lost during the request.

Shall I call my isNetworkAvailable method in the while loop (which means lots of calls)? What's the standard way to manage connection lost with HttpURLConnection?

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

FileOutputStream outputStream = openFileOutput(filename, MODE_PRIVATE | MODE_APPEND);               

BufferedInputStream in = new BufferedInputStream(connection.getInputStream());

byte[] data = new byte[1024];
int x = 0;

while ((x = in.read(data, 0, 1024)) >= 0) {
    outputStream.write(data, 0, x);
}

Upvotes: 0

Views: 1441

Answers (1)

Jules
Jules

Reputation: 15199

I'd suggest catching IOException and if it happens, giving the user an option to retry or cancel. You may want to use setConnectTimeout (see HttpURLConnection timeout question for an example of how to use it) to make sure you get an error in a reasonable time.

As a random comment -- if you're reading data into a reasonably large buffer, as you are here, there's little or no point using a BufferedInputStream; just use the input stream returned by connection.getInputStream() directly. The only reason to use a BufferedInputStream is if you're reading in small chunks, e.g. one byte at a time.

Upvotes: 1

Related Questions