我为URLConnections的基本GET和POST请求实现了一个WebRequest类。
其中一项功能是提交文件 - 现在我想计算并显示上传文件的进度 - 但我不知道该怎么做:
for (KeyFilePair p : files) {
if (p.file != null && p.file.exists()) {
output.writeBytes("--" + boundary + "\n");
output.writeBytes("Content-Disposition: form-data; name=\""
+ p.key + "\"; filename=\"" + p.file.getName() + "\"\n");
output.writeBytes("Content-Type: " + p.mimetype
+ "; charset=UTF-8\n");
output.writeBytes("\n");
InputStream is = null;
try {
long max = p.file.length();
long cur = 0;
is = new FileInputStream(p.file);
int read = 0;
byte buff[] = new byte[1024];
while ((read = is.read(buff, 0, buff.length)) > 0) {
output.write(buff, 0, read);
output.flush();
cur += read;
if (monitor != null) {
monitor.updateProgress(cur, max);
}
}
} catch (Exception ex) {
throw ex;
} finally {
if (is != null) {
try {
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
output.writeBytes("\n--" + boundary + "--\n");
在此代码中,您可以看到OutputStream输出的写入字节的基本计算。 但由于在打开连接的InputStream(或读取状态代码)之前,请求甚至没有发送到服务器,因此这个字节计数完全没用,只显示请求准备的进度。
所以我的问题是: 如何监控实际发送到服务器的字节的当前状态?我已经检查了相应类(HttpUrlConnection)的getInputStream的Java源代码,试图了解实际字节写入服务器的方式和时间......但是没有结论。
如果没有编写自己的http协议实现,有没有办法做到这一点?
由于
祝你好运 亚光
答案 0 :(得分:6)
您必须设置conn.setChunkedStreamingMode(-1); // use default chunk size
。
如果没有,HUC正在缓冲整个数据只是为了知道要设置为Content-Length
的值。你实际上正在监控缓冲过程。
作为替代方案,您可以计算多部分身体的大小(祝您好运!)并致电conn.setFixedLengthStreamingMode(lengthInBytes)
。
您可以在HttpUrlConnection multipart file upload with progressBar
上找到更多信息