2014-03-25 34 views
5

Java的HttpURLConnection的状态我实现了一个WebRequest类为我的基本GET和POST请求的URLConnections。实际发送的字节

的特点之一,是提交的文件 - 现在,我想计算并显示上传文件的进度 - 但我不知道该怎么做:

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我的连接的(或读取的StatusCode)的服务器,该字节计数是completelly无用,而仅显示该请求准备的进展情况。

所以我的问题是: 如何监控的实际发送字节的当前状态的服务器?我已经检查了相应类(HttpUrlConnection)的getInputStream的Java源,试图了解实际上如何以及何时将字节写入服务器......但没有任何结论。

有没有办法做到这一点没有写我自己实现的HTTP protocoll的?

感谢

问候 亚光

回答

6

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

如果没有,HUC正在缓冲整个数据只知道哪个值设置为Content-Length。你实际上在监视缓冲过程。

作为替代,你可以计算出你的多部本体的尺寸(祝你好运!),并调用conn.setFixedLengthStreamingMode(lengthInBytes)

更多详情请登录HttpUrlConnection multipart file upload with progressBar

+0

非常感谢 - 它的作品:) – matt