Efficient and fast way to send data from Android to server I have an app that will be sending images ranging from few KB to ~20MB and I need to write a code that will do that in the fastest and most efficient way. I currently have a code that does this, but I fear that it's inefficient and slow:

// Read bitmap from file
Bitmap bitmap = null;
Uri uri = Uri.fromFile(new File("camera/myfile.jpg"));
InputStream stream = null;

try {
    stream = getContentResolver().openInputStream(uri);
    BitmapFactory.Options options = new BitmapFactory.Options();
    bitmap = BitmapFactory.decodeStream(stream, null, options);
} catch (IOException e) {
    Log.e(TAG, e.getMessage(),e);
    return null;
} finally {
    try {
        if (stream != null) stream.close();
    } catch (Exception e) {}
}

// Send image data to server
ByteArrayOutputStream byteStream = null;

try {
    // Create HTTP objects
    DefaultHttpClient httpClient = new DefaultHttpClient();
    BasicHttpParams hparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(hparams,10*1000);
    httpClient.setParams(hparams);
    HttpPost httpPost = new HttpPost(my_servers_url);

    byteStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteStream);

    // Convert ByteArrayOutputStream to byte array. Close stream.
    byte[] byteArray = byteStream.toByteArray();
    byteStream.close();
    byteStream = null;

    // Send HTTP Post request
    httpPost.setEntity(new ByteArrayEntity(byteArray));
    String response = EntityUtils.toString(httpClient.execute(httpPost).getEntity(), HTTP.UTF_8);

} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (byteStream != null) byteStream.close();
    } catch (Exception e) {}
}


My concern is that the entirety of the image is loaded into a byte array on the device before being sent to the server. Although this code works, it is slower than what I'm satisfied with.

Can this code be faster and more efficient? Would it be better to use HttpURLConnection instead? If so, how would I write the code?
The code can be made more memory efficient if you refactor it to use HttpURLConnection.

If you wish to write your own solution to upload the video file instead of using a 3rd party library, you can use HttpURLConnection to create a "read-write" while loop.  In this while-loop, while bytes have been read, read either InputFileStream up to a maxBufferSize OR available bytes left in the InputFileStream and store it into a buffer array (max array size is maxBufferSize). Then write this buffer array into HttpURLConnection's DataOutputStream.

If you can post new code that implements this approach in a background thread/service, then we could review that.