I need to upload an image from Android along with other data to a JSON web service. The problem is that i can't find a way to do it all at once.
Here is the code I use to make the request:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) throws JSONException {
try {
if (method == "POST") {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
//...
}
} catch (Exception e) {
//...
}
//...
// Parse response and return json object
return null;
}
Here is the code I use to fill the params parameter:
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("first_name", "John"));
params.add(new BasicNameValuePair("last_name", "Doe"));
params.add(new BasicNameValuePair("image", ??));
I've tried using the image path in the SDCard with no results, also the image as a String with the code below with no results.
Bitmap bitmap = BitmapFactory.decodeFile(group.getImgPath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String strBitMap = Base64.encodeToString(b, Base64.DEFAULT);
params.add(new BasicNameValuePair("image", strBitMap));
When I use a mutlipart entity then I don't know how to set the params object, only the image. The problem is that I need to upload all data including the image at once.
Any solutions?
Thanks in advance.