2013-08-07 41 views
11

Android Developers Blog推荐使用HttpURLConnection,而不是Apache的HttpClienthttp://android-developers.blogspot.com/2011/09/androids-http-clients.html)。我接受建议 ,并在报告文件上传进度时遇到问题。有没有什么办法可以使用HttpUrlConncetion正确获取上传进度

我的代码抢进度是这样的:

try { 
    out = conncetion.getOutputStream(); 
    in = new BufferedInputStream(fin); 
    byte[] buffer = new byte[MAX_BUFFER_SIZE]; 
    int r; 
    while ((r = in.read(buffer)) != -1) { 
     out.write(buffer, 0, r); 
     bytes += r; 
     if (null != mListener) { 
      long now = System.currentTimeMillis(); 
      if (now - lastTime >= mListener.getProgressInterval()) { 
       lastTime = now; 
       if (!mListener.onProgress(bytes, mSize)) { 
        break; 
       } 
      } 
     } 
    } 
    out.flush(); 
} finally { 
    closeSilently(in); 
    closeSilently(out); 
} 

这个代码excutes非常快无论文件大小,但文件却仍然上传到服务器UTIL我得到来自服务器的响应。当我呼叫out.write()时,似乎HttpURLConnection将内部缓冲区中的所有数据都缓存起来。

所以,我怎样才能得到实际的文件上传进度?似乎httpclient可以做到这一点,但 httpclient不首选...任何想法?

+1

因为成为不使用apache客户端的明智开发人员之一,您会获得惊人的+1。在这个网站上,以apache客户端的名义看到了一些Android中最糟糕的网络决策。其次,通常进度与上传大文件有关。你的档案有多大?如果是这样,分块传输编码适合您的文件? – Tom

+0

@汤姆我的应用程序需要支持不超过30m较大的上传文件,并在服务器端不支持现在块传输编码... – toki

+0

@Toki这是旧的,但如果你想知道你拼错在第2行 – charliebeckwith

回答

14

的进展,我发现在开发文档http://developer.android.com/reference/java/net/HttpURLConnection.html

To upload data to a web server, configure the connection for output using setDoOutput(true). 
For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance, or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly exhausting) heap and increasing latency. 

调用setFixedLengthStreamingMode()首先解决我的问题的解释。 但正如this post提到的,采用的是Android,使得HttpURLConnection高速缓存,即使setFixedLengthStreamingMode()已调用的所有内容,这是不固定的,直到Froyo版后的错误。所以我用HttpClient代替姜饼。

+0

这是我在StackOverflow上读到的关于这个问题的最有用的东西。许多人只是追踪写入缓冲区并认为他们解决了问题。 – Brian

+0

@toki,现在这个bug的状态如何? – avismara

-2

使用的AsyncTask在

publishProgress("" + (int) ((total * 100)/lenghtOfFile)); 
    //type this in the while loop before write.. 

3上传文件,将文件上传到服务器并创建Progressdialog

1)

doinbackground(){ 
    your code here.. 
} 

2运行代码)更新进度),并在更新进度

protected void onProgressUpdate(String... progress) { 
      Progress.setProgress(Integer.parseInt(progress[0])); 
     } 

4)驳回

protected void onPostExecute(String file_url) { 
      dismissDialog(progress); 
+0

连接我不认为OP在为此制作UI方面遇到问题。 OP希望得到一个可靠的解释,即有多少数据流已被读取到套接字上。 “总数”来自哪里? – Tom

+0

Tom是对的,我想要一种方法在上传文件时获取网络传输进度,这正是多少字节已经发送到套接字层上的服务器。 – toki

相关问题