我有一个可以使用互联网连接下载数据的应用程序。我使用HttpURLConnection
来做到这一点。下载时限制带宽
问题:我的应用程序耗尽了互联网带宽,因此用户将在他们的浏览器上缓慢浏览。我想让它们自己设置带宽限制,而不是像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) {}
}
}
}
对不起,它没有给出确切的限制。 – 2015-02-13 11:38:03
这不*设置*一个限制,只是提供各种信息。 – EJP 2015-03-15 05:51:45