HttpUrlConnection buffers the data so that it can set the Content-Length header (per HTTP specification ).
One option, if your target server supports it, is to use " chunked ". This will only delay a small portion of the data at a time. However, not all services support it (for example, Amazon S3).
Another alternative (and imo is better) is to use Jakarta HttpClient . You can set the "entity" in the request from a file, and the connection code will correctly configure the request headers.
Edit: nos commented that the OP might call HttpURLConnection.setFixedLengthStreamingMode(long length) . I did not know about this method; It was added in 1.5, and I have not used this class since.
However, I still suggest using Jakarta HttpClient for the simple reason that it reduces the amount of code that the OP should support. Code that is a template but still has the potential for errors:
- The OP correctly handles the loop for copying between input and output. Usually, when I see an example of this, the poster either incorrectly checks the size of the returned buffer, or saves the re-allocation of buffers. Congratulations, but now you have to make sure that your successors take great care.
- Exception handling is not so good. Yes, the OP remembers to close the connections in the
finally block, and again, congratulations on that. Except that any of the close() calls might throw an IOException , leaving the other to execute. And the method as a whole throws an Exception , so the compiler is not going to catch such errors. - I am counting 31 lines of code to configure and execute the response (excluding checking the response code and calculating the URL, but including try / catch / finally). With HttpClient, it will be somewhere in the range of half a dozen LOCs.
Even if the OP wrote this code perfectly and reorganized it into methods similar to the methods in Jakarta Commons IO, he / she should not. This code has been written and verified by others. I know that it is a waste of time to rewrite it, and suspect that it is also a waste of time OP.
kdgregory Jan 17 '10 at 18:25 2010-01-17 18:25
source share