Mar 10

When using URLConnection (HttpURLConnection actually) to send a large POST you can often get a OutOfMemoryError, for example when POSTing a large file.

Reason for this is that by default HttpURLConnection buffers the entire POST to enable it to set the content length for the request.

If you already know the content length in advance (for example when sending a file) you can use streaming mode.

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setFixedLengthStreamingMode(file.length());

// now write file to connections output stream

written by objects \\ tags: , , , ,


Leave a Reply

You must be logged in to post a comment.