Jonathan Viccary
Jonathan Viccary

Reputation: 732

Retrofit image upload returns 415 Unsupported Media Type

I have a REST Resource using JBoss & RestEasy as follows

@Path(ServiceURL.MEDIA)
public class ImageUploadService {

    @POST
    @Consumes({APPLICATION_OCTET_STREAM})
    public Response upload(@QueryParam("contenttype") String contentType, InputStream input, @Context HttpServletRequest request) throws IOException {
    ...
    }
}

and a Retrofit interface in an Android project as follows:

public interface ImageUploadService {

    @Multipart
    @POST(ServiceURL.BASE + ServiceURL.MEDIA)
    public Response upload(@Query("contenttype") String contentType, @Part("image") TypedByteArray input);
}

which is invoked via

ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapData = bos.toByteArray();
RestAdapter ra = new RestAdapter.Builder()
                 .setEndpoint(hostURL)
                 .setClient(new MediaClient())
                 .build();
ImageUploadService imageUploadService = ra.create(ImageUploadService.class);
TypedByteArray typedByteArray = new TypedByteArray(MediaType.APPLICATION_OCTET_STREAM, bitmapData);
imageUploadService.upload("image/png", typedByteArray);

and the MediaClient is

public class MediaClient extends OkClient {

    @Override
    protected HttpURLConnection openConnection(Request request) throws IOException {
        HttpURLConnection connection = super.openConnection(request);
        connection.setRequestMethod(request.getMethod());

        connection.setRequestProperty("Accept", MediaType.APPLICATION_OCTET_STREAM);

        return connection;
    }
}

However the service returns a 415 Unsupported Media Type and the method body of the service resource is not invoked, implying RestEasy is rejecting the request.

Any ideas?

Upvotes: 2

Views: 6391

Answers (1)

Jonathan Viccary
Jonathan Viccary

Reputation: 732

The problem was the MediaClient. Firstly,

connection.setRequestProperty("Accept", MediaType.APPLICATION_OCTET_STREAM);

should have been

connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM);

Secondly, the TypedByteArray handles this, and repetition of "application/octet-stream" was causing RestEasy to fail parsing "application/octet-stream, application/octet-stream" as a MediaType. So I removed the client altogether.

Upvotes: 1

Related Questions