jersey - 使用球衣,我如何为错误生成 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)。
解决方案
这可能会起作用,因为您的异常说它找不到消息编写器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();
}
}
推荐阅读
- ios - 如何分别使用 Alamofire 发送参数和正文?
- reactjs - 我需要将我的 Apollo 客户端缓存设置为默认值
- python - 如何使用比较语句在 python 中进行 REST 查询?
- ios - 在 Visual Studio App Center 中导入框架(使用 Carthage)时命令“CompileSwift normal arm64”失败
- mobile - 移动优先索引是否意味着以较低的分辨率开发?
- python - 在进程完成之前,Flask 多处理不会返回响应
- angular - Angular 4 过滤按钮点击
- web-services - 我们如何在 Hybris 6.7 的 oauth 响应中传递用户详细信息
- python - Python Urllib 下载视频但无法播放
- html - 如何在 onsenui navigator 中使用多个 html