我有一个应用程序,可以利用互联网连接下载数据。我正在使用
HttpURLConnection
完成此操作。
问题:我的应用会耗尽互联网带宽,因此用户使用浏览器时会变慢。 我想让他们自行选择设置带宽限制,而不像这个网站那样。我已经了解过这个了。
问题:如何在下载时设置带宽限制?例如:500 KB / s(每秒字节)。
以下是我的下载文件方法:// These are the status codes.
public static final int DOWNLOADING = 0;
public static final int PAUSED = 1;
public static final int COMPLETE = 2;
public static final int CANCELLED = 3;
public static final int ERROR = 4;
private long downloaded;
private int status;
private void downloadFile(String requestUrl) throws IOException {
InputStream stream = null;
RandomAccessFile output = null;
status = DOWNLOADING;
downloaded = 0;
URL url = new URL(requestUrl);
try {
System.setProperty("http.keepAlive", "false");
output = new RandomAccessFile(my_directory, "rw");
// Open connection to URL.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.connect();
// Make sure response code is in the 200 range.
int statusCode = connection.getResponseCode();
if (statusCode != 200) {
status = ERROR;
}
stream = connection.getInputStream();
while (status == DOWNLOADING) {
byte buffer[] = new byte[1024];
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1)
break;
// Write buffer to file.
output.write(buffer, 0, read);
downloaded += read;
}
status == COMPLETE;
} catch (Exception e) {
status = ERROR;
} finally {
if (output != null) {
try {
output.close();
} catch (Exception e) {}
}
// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {}
}
}
}