gpt4 book ai didi

java - 下载时限制带宽

转载 作者:太空狗 更新时间:2023-10-29 15:00:33 25 4
gpt4 key购买 nike

我有一个可以使用互联网连接下载数据的应用程序。我正在使用 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) {}
}
}
}

最佳答案

如果您有一个 Socket,您可以将接收缓冲区大小设置为所需的带宽延迟乘积,但是,如果没有,您将不得不在接收调用之间 hibernate 。实验或一些基于反馈的算法将产生适当的 sleep 间隔。

关于java - 下载时限制带宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27317857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com