Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Upload an Image to a Web Service Using HttpURLConnection

DZone's Guide to

Upload an Image to a Web Service Using HttpURLConnection

Learn how to upload an image from Android

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

The following code snippet can be used to upload an image to web service in Android. After getting a Bitmap object from the camera or other source, you can compress the create an HttpURLConnection and attach the image to the request body.


try {
URL url = new URL(SERVER_POST_URL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setDoInput(true);
c.setRequestMethod("POST");
c.setDoOutput(true);
c.connect();

OutputStream output = c.getOutputStream();
bitmap.compress(CompressFormat.JPEG, 50, output);
output.close();

Scanner result = new Scanner(c.getInputStream());
String response = result.nextLine();
Log.e("ImageUploader", "Error uploading image: " + response);

result.close();
} catch (IOException e) {
Log.e("ImageUploader", "Error uploading image", e);
}

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

Topics:
upload ,file upload

Published at DZone with permission of Nilanchala Panigrahy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}