Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit2 Post image as base64

i've been using Retrofit for a long time but after this huge update, it's been little bit hard :) My issue is i need to send a post request as formUrlEncoded within an image encoded base64.

Without image, the below request works just fine

@FormUrlEncoded
@POST("mypath")
Call<BooleanResponse> updateUser(@FieldMap HashMap<String, String> updatedValues);

But when i tried to include image, Base64 encoded as well then i get Internal Server Error -which i know it is not about server side because i have another application calling this service with HttpPost and that works just fine.

This is how i get base64 data from image and i add this into map that i'll pass to updateUser request as well, but that's just not working.

public static String getProfileImage(ImageView imageView) {
    imageView.buildDrawingCache();
    Bitmap bm = imageView.getDrawingCache();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
    byte[] b = baos.toByteArray();
    return Base64.encodeToString(b, Base64.DEFAULT);
}

As i searched, i found that Retrofit use some serializations on request via Gson unless i tell it not to do so! As in this question

But i couldn't figure out how to put it as in Retrofit2, any suggestions?

like image 963
yahya Avatar asked Jan 29 '16 12:01

yahya


1 Answers

I found the solution. Updated service request as below

@POST("mypath")
Call<BooleanResponse> updateUser(@Body RequestBody updatedBody);

And created a RequestBody object from updatedValues map and used above request instead.

FormBody.Builder bodyBuilder = new FormBody.Builder();
Iterator it = changedFieldsMap.entrySet().iterator();
while (it.hasNext()) {
      Map.Entry pair = (Map.Entry) it.next();
      bodyBuilder.add((String) pair.getKey(), (String) pair.getValue());
      it.remove(); // avoids a ConcurrentModificationException
}
RequestBody requestBody = bodyBuilder.build();
serviceManager.updateUser(requestBody);
like image 181
yahya Avatar answered Oct 17 '22 07:10

yahya