我有一个可以使用互联网连接下载数据的应用程序.我正在使用HttpURLConnection来做到这一点.
问题:我的应用程序消耗了Internet带宽,因此用户将在其浏览器上缓慢浏览.我想让他们选择自己设置带宽限制,而不是像this site.我已经知道了.
问题:下载时如何设置带宽限制?例如: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) {}
}
}
}