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 tried the solutions above and none worked for me out of the box.
However http://www.baeldung.com/httpclient-post-http-request. Line 6 POST Multipart Request worked within seconds
I found using okHttp a lot easier as I could not get any of these solutions to work: https://stackoverflow.com/a/37942387/447549
I actually found a better way to send files using HttpURLConnection using MultipartEntity
Assuming you are uploading an image with bitmap data:
And Voila! Your post data will contain picture field along with the filename and path on your server.
I haven't tested this, but you might try using PipedInputStream and PipedOutputStream. It might look something like:
based on Mihai's solution, if anyone has the problem of saving images on the server like what happened on my server. change the Bitmap to bytebuffer part to :
Here is what i did for uploading photo using post request.
NOTE: This code requires libraries so Follow the instructions here in order to get the libraries.