首页 > 解决方案 > 使用球衣,我如何为错误生成 json 并为成功生成八位字节流

问题描述

问题的简短版本:

使用 Jersey,如何@Produces在运行时确定类型?

问题的长版本:

我使用 jersy 编写了一个 REST 调用,如下所示:

@GET
@Path("/getVideo")
@Consumes(MediaType.APPLICATION_JSON)
@Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
public Response getAllVideos(@QueryParam("videoID") Long videoID) throws ApiException, SQLException {
    --some code--
    Response r ...;
    return r;
}

如果用户提供了有效的,videoID那么这应该返回一个mp4文件,因此@Produces({MediaType.APPLICATION_OCTET_STREAM,. 但是,如果抛出异常,例如提供错误,videoID我想返回一个json描述异常的信息。

它目前的工作方式是,如果提供了有效的 ID,它会返回一个200带有 mp4 文件的文件。但是如果抛出异常,它会以 a500和 message响应Could not find MessageBodyWriter for response object of type: com.my.package.Errors$CustomError of media type: application/octet-stream

根据Jersey 文档,响应的返回类型取决于accept请求的类型。

我的问题是我事先不知道,在发送请求时我想要返回什么类型的响应(因为我希望请求会成功)。相反,我想根据是否引发异常来确定运行时的响应类型。

我怎样才能做到这一点?

(我认为我的问题与这个问题相似,但我没有使用 Spring)。

标签: jerseyjax-rs

解决方案


这可能会起作用,因为您的异常说它找不到消息编写器CustomError

@Provider
@Produces(MediaType.APPLICATION_OCTET_STREAM) //I think you will have to leave this as octet_stream so jax-rs will pick as valid message writer
public class CustomErrorBodyWriter implements MessageBodyWriter<CustomError> {

    @Override
    public boolean isWriteable(Class<?> type, Type genericType,
                               Annotation[] annotations, MediaType mediaType) {
        return type == CustomError.class;
    }

    @Override
    public long getSize(CustomError customError, Class<?> type, Type genericType,
                        Annotation[] annotations, MediaType mediaType) {
        // deprecated by JAX-RS 2.0 and ignored by Jersey runtime
        return 0;
    }

    @Override
    public void writeTo(CustomError customError, Class<?> type, Type genericType, Annotation[] annotations,
                        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
                        OutputStream out) throws IOException, WebApplicationException {

        //manipulate the httpHeaders  to have content-type application/json

        //transalate customError and write it to OutputStream          

        Writer writer = new PrintWriter(out);
        writer.write("{ \"key\" : \"some random json to see if it works\" }");


        writer.flush();
        writer.close();
    }
}

推荐阅读