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.
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);
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