Why does HTTPURLConnection.getInputStream() takes time

前端 未结 2 1171
北荒
北荒 2020-12-11 22:53

I have a task to download & upload a file using HTTP protocol in Android (Java platform).

I am using following code for uploading a file:

HttpURL         


        
2条回答
  •  甜味超标
    2020-12-11 23:48

    You must limit buffering by specifying the streaming mode either by giving the final length of the uploaded information via setFixedLengthStreamingMode method, or setting mode to streaming if final length is not known via setChunkedStreamingMode method:

        // 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.
        //
        // see: https://developer.android.com/reference/java/net/HttpURLConnection.html
    
        _connection.setChunkedStreamingMode(1024);
    

    If you don't, the real transfer will occur when you call getInputStream().

    See https://developer.android.com/reference/java/net/HttpURLConnection.html

提交回复
热议问题