android - Retrofit 图片上传返回 415 Unsupported Media Type

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

我有一个使用 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/

相关文章:

android - 如何使android中 View 周围的区域变暗?

java - 使用 Java Rally Rest API 在 rally 中将测试用例添加到 TestSets

java - 无法遍历 JSON 数组

c# - 无法使用 Jive REST API 发布共享 - 出现 400 Bad Request 错误

rest - 如何防止经过身份验证的用户欺骗restful api调用

Android,无法使用 Retrofit 和 RxJava 2 构建应用程序

java - 使用异步改造调用在模型中执行附加逻辑

android - 具有身份验证的服务器上的 ECONNRESET(对等方重置连接)

android - setEGLConfigChooser() 中的 "depthSize"和 "stencilSize"是什么意思?

android - android 中的 ActionBar API