0

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);
}
jul
  • 36,404
  • 64
  • 191
  • 318

1 Answers1

1

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.

Community
  • 1
  • 1
Jules
  • 14,841
  • 9
  • 83
  • 130
  • Ok, I've just seen that `IOException` has a `ConnectException` subclass. I'll use that, thanks. About the `BufferedInputStream`: I need small chunks to display the download progress. – jul Jul 13 '13 at 09:23