This is a generic method I'm using to send POST to the backend:
/**
* putJSONObject
*
* @param url
* @param jsonObject
* @param timeoutMillis
* @return
*/
protected static JSONObject putJSONObject (String url, JSONObject jsonObject, int timeoutMillis) throws IOException, JSONException {
StringBuilder stringBuilder = new StringBuilder ();
HttpURLConnection httpURLConnection;
DataOutputStream printout;
httpURLConnection = (HttpURLConnection) new URL (url).openConnection ();
httpURLConnection.setRequestMethod ("POST");
httpURLConnection.setReadTimeout (timeoutMillis);
httpURLConnection.setConnectTimeout (timeoutMillis);
httpURLConnection.setDoInput (true);
httpURLConnection.setDoOutput (true);
httpURLConnection.setUseCaches (false);
httpURLConnection.connect ();
// Send POST output.
printout = new DataOutputStream (httpURLConnection.getOutputStream ());
printout.writeBytes ("msg=" + URLEncoder.encode (jsonObject.toString (), "UTF-8"));
printout.flush ();
printout.close ();
InputStreamReader inputStreamReader = new InputStreamReader (httpURLConnection.getInputStream ());
int read;
char[] buff = new char[4096];
while ((read = inputStreamReader.read (buff)) != -1) {
stringBuilder.append (buff, 0, read);
}
httpURLConnection.disconnect ();
return new JSONObject (stringBuilder.toString ());
}
The JSON sent is sent as 'msg'
and for encoding the picture to an string this is my code:
/**
* toBase64
*
* @param bitmap
* @return String
*/
public static String toBase64 (Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
/**
* fromBase64
*
* @param encodedImage
* @return Bitmap
*/
public static Bitmap fromBase64 (String encodedImage) {
byte[] decodedByte = Base64.decode(encodedImage, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
Hope it helps you.