我有一個可以使用互聯網連接下載數據的應用程序。我使用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