如何使用HttpURLConnection管理丢失的连接? [英] How to manage connection lost with HttpURLConnection?

查看:72
本文介绍了如何使用HttpURLConnection管理丢失的连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Service,可以使用HttpURLConnection管理下载任务.

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

我在执行任何HTTP请求之前都使用了自定义的isNetworkAvailable方法,但是我想知道如何处理在请求期间丢失的连接.

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

我应该在while循环中调用我的isNetworkAvailable方法(这意味着很多调用)吗?用HttpURLConnection管理丢失的连接的标准方法是什么?

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

推荐答案

我建议捕获IOException,如果发生,请为用户提供重试或取消的选项.您可能要使用setConnectTimeou t(有关如何使用它的示例,请参见 HttpURLConnection超时问题 ),以确保您在合理的时间内收到错误消息.

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.

作为一个随机注释-如果您正将数据读入相当大的缓冲区中(如您在此处),则使用BufferedInputStream几乎没有意义.只需直接使用connection.getInputStream()返回的输入流即可.使用BufferedInputStream的唯一原因是如果您正在阅读小块内容,例如一次一个字节.

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.

这篇关于如何使用HttpURLConnection管理丢失的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆