改造图像上传返回415不支持的媒体类型

时间:2015-02-03 15:24:55

标签: android rest retrofit http-status-code-415

我有一个使用JBoss&的REST资源。 RestEasy如下

@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 {
    ...
    }
}

和Android项目中的Retrofit界面如下:

public interface ImageUploadService {

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

通过

调用
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);

并且MediaClient是

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;
    }
}

但是,该服务返回415 Unsupported Media Type并且未调用服务资源的方法体,这意味着RestEasy拒绝该请求。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

问题在于MediaClient。首先,

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

应该是

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

其次,TypedByteArray处理这个问题,并且重复“application / octet-stream”导致RestEasy无法解析“application / octet-stream,application / octet-stream”作为MediaType。所以我完全删除了客户端。