【问题标题】:Retrofit image upload returns 415 Unsupported Media Type改造图片上传返回 415 Unsupported Media Type
【发布时间】:2015-02-03 15:24:54
【问题描述】:

我有一个使用 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 正在拒绝请求。

有什么想法吗?

【问题讨论】:

  • 当我尝试从服务器获取“application/json”数据时遇到了类似的问题。所以我只是将 @Headers("Accept: application/json") 添加到改造界面。这适用于改造 2.0.0。

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


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2020-07-30
    • 2018-06-10
    相关资源
    最近更新 更多