【发布时间】:2014-05-02 22:56:55
【问题描述】:
我为对 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 协议实现的情况下做到这一点?
谢谢
最好的问候 马特
【问题讨论】:
标签: java upload httpurlconnection status outputstream