2

我有一个使用 JBoss 和 RestEasy 的 REST 资源,如下所示

@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 正在拒绝请求。

有任何想法吗?

4

1 回答 1

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。所以我完全删除了客户端。

于 2015-02-03T16:37:47.787 回答