【问题标题】:Java HttpUrlConnection status of actually sent bytes实际发送字节的 Java HttpUrlConnection 状态
【发布时间】: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


    【解决方案1】:

    你必须设置conn.setChunkedStreamingMode(-1); // use default chunk size

    如果不是,HUC 正在缓冲整个数据,只是为了知道将哪个值设置为Content-Length。您实际上是在监视缓冲过程。

    作为替代方案,您可以计算多部分身体的大小(祝您好运!)并致电conn.setFixedLengthStreamingMode(lengthInBytes)

    您可以在HttpUrlConnection multipart file upload with progressBar 上找到更多信息

    【讨论】:

    • 所以,如果您要在文件上使用缓冲流,那么我不会看到同样的问题,因为在我开始阅读之前,缓冲流已经缓冲了它(在引擎盖下),对吧?
    猜你喜欢
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2011-01-06
    • 2011-03-26
    相关资源
    最近更新 更多