java web 下载文件带宽限制_java-下载时限制带宽

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

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值