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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With