6

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.

M.S.
  • 1,091
  • 1
  • 11
  • 27
  • instead of using `@RequestBody`, use `@Part` – Ankit Aggarwal Apr 13 '16 at 02:46
  • You can use `Call postFile(@Part MultipartBody.Part file, @Part("description") RequestBody description);`. Please read http://stackoverflow.com/questions/36491096/retrofit-multipart-request-required-multipartfile-parameter-file-is-not-pre/36514662#36514662 – BNK Apr 13 '16 at 04:27

1 Answers1

1

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);
sapht
  • 2,789
  • 18
  • 16
Ankit Aggarwal
  • 5,317
  • 2
  • 30
  • 53
  • Thanks, but the `RequestBody` still seems to send `{}` to the server. – M.S. Apr 13 '16 at 03:10
  • 2
    The error has now been fixed by @sapht, but in the future: if your answer needs a correction, click the question's "edit" link and fix it. The comments are a place to say "Oops, needed to change X to Y, that's done now", not "Would someone please change X to Y?" – Paul Roub Jul 18 '16 at 17:48