我在下面提供了宁静的网络服务代码。但是当访问web服务时,我得到“找不到MIME媒体类型application / pdf”。 docService.findByVersionId确实返回一个“TestDoc”,它将pdf内容保存为byte []。
你能帮我解决这个问题吗?
@GET
@Path("/getPdf/{versionId}")
@Produces("application/pdf")
public Response getPdfFile(@PathParam("versionId") final String versionId) {
try {
final TestDoc doc = this.docService.findByVersionId(versionId);
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final BufferedOutputStream bos = new BufferedOutputStream(byteArrayOutputStream);
final byte[] pdfContent = doc.getPdfDoc();
bos.write(pdfContent);
bos.flush();
bos.close();
return Response.ok(byteArrayOutputStream).build();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
错误:
Exception:
2014-01-02 12:42:07,497 ERROR [STDERR] 02-Jan-2014 12:42:07 com.sun.jersey.spi.container.ContainerResponse write
SEVERE: A message body writer for Java class java.io.ByteArrayOutputStream, and Java type class java.io.ByteArrayOutputStream, and MIME media type application/pdf was not found
答案 0 :(得分:1)
您似乎无法使用ByteArrayOutputStream。解决方案是使用StreamingOutput。
@GET
public Response generatePDF(String content) {
try {
ByteArrayOutputStream outputStream = service.generatePDF(content);
StreamingOutput streamingOutput = getStreamingOutput(outputStream);
Response.ResponseBuilder responseBuilder = Response.ok(streamingOutput, "application/pdf");
responseBuilder.header("Content-Disposition", "attachment; filename=Filename.pdf");
return responseBuilder.build();
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
return Response.serverError().build();
}
}
private StreamingOutput getStreamingOutput(final ByteArrayOutputStream byteArrayOutputStream) {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
byteArrayOutputStream.writeTo(output);
}
};
}