Since the Android developers recommend to use the HttpURLConnection class, I was wondering if anyone can provide me with a good example on how to send a bitmap “file” (actually an in-memory stream) via POST to an Apache HTTP server. I’m not interested in cookies or authentication or anything complicated, but I just want to have a reliable and logic implementation. All the examples that I’ve seen around here look more like “let’s try this and maybe it works”.
Right now, I have this code:
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://example.com/server.cgi");
urlConnection = (HttpURLConnection) url.openConnection();
} catch (Exception e) {
this.showDialog(getApplicationContext(), e.getMessage());
}
finally {
if (urlConnection != null)
{
urlConnection.disconnect();
}
}
where showDialog should just display an AlertDialog (in case of an invalid URL?).
Now, let’s say that I generate a bitmap like so: Bitmap image = this.getBitmap() inside a control derived from View and I want to send it via POST. What would be the proper procedure to achieve such a thing? What classes do I need to use? Can I use HttpPost like in this example? If so, how would I construct the InputStreamEntity for my bitmap? I would find it revolting to be required to first store the bitmap in a file on the device.
I should also mention that I really need to send every unaltered pixel of the original bitmap to the server, so I can’t convert it to JPEG.
I have no idea why the
HttpURLConnectionclass does not provide any means to send files without having to compose the file wrapper manually. Here’s what I ended up doing, but if someone knows a better solution, please let me know.Input data:
Static stuff:
Setup the request:
Start content wrapper:
Convert
BitmaptoByteBuffer:End content wrapper:
Flush output buffer:
Get response:
Close response stream:
Close the connection:
PS: Of course I had to wrap the request in
private class AsyncUploadBitmaps extends AsyncTask<Bitmap, Void, String>, in order to make the Android platform happy, because it doesn’t like to have network requests on the main thread.