Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct Way to Post Binary Data Using Retrofit 2.0

I have recently moved from using Retrofit 1.9 to Retrofit 2, and am experiencing a problem in posting binary data.

When I was using Retrofit 1.9, I was able to send a TypedByteArray that contained byte[] data as the @Body of a request. The closest equivalent to TypedByteArray seems to be RequestBody, which I am using as follows:

final ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 5, byteOutputStream);
final byte[] thumbnailBytes = byteOutputStream.toByteArray();
final RequestBody thumbnailRequestBody = RequestBody.create(MediaType.parse("image/jpeg"), thumbnailBytes);

The code to generate the request is below:

Headers("Content-Type: image/jpeg")
@POST("/thumbnail")
Call<Void> uploadThumbnail(@Body RequestBody thumbnailContent);

However, it seems that Retrofit may be trying to parse the RequestBody as a JSON object, since the data that actually gets sent to the server is {}.

Any advice or guidance on how to correctly post binary data would be appreciated. Thanks.

like image 432
M.S. Avatar asked Apr 13 '16 02:04

M.S.


1 Answers

Create your request like this

Headers("Content-Type: image/jpeg")
@POST("/thumbnail")
@Multipart
Call<Void> uploadThumbnail(@Part RequestBody thumbnailContent);

Call it like this

File partFile = <your_stream_as_file>;
RequestBody fbody = RequestBody.create(MediaType.parse("image"), partFile);
uploadThumbnail(fbody);
like image 82
Ankit Aggarwal Avatar answered Oct 05 '22 12:10

Ankit Aggarwal