我有一个使用 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);
媒体客户端是
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 正在拒绝请求。
有什么想法吗?
最佳答案
问题出在 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。所以我完全删除了客户端。
关于android - Retrofit 图片上传返回 415 Unsupported Media Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28302538/