How to manage connection lost with HttpURLConnection?

為{幸葍}努か 提交于 2019-12-25 07:06:46

问题


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);
}

回答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.



来源:https://stackoverflow.com/questions/17628688/how-to-manage-connection-lost-with-httpurlconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!