【发布时间】:2015-01-28 11:37:37
【问题描述】:
我在 Response 对象中返回一个 StreamingOutput:
@GET
@Path("/downloadFile/{filename}")
@Produces(MediaType.TEXT_PLAIN)
public Response downloadFile(@PathParam("filename") String fileName) {
LOG.debug("called: downloadFile({})", fileName);
final File f = new File("/tmp/" + fileName);
try {
if (f.exists()) {
StreamingOutput so = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException,
WebApplicationException {
FileInputStream fis = new FileInputStream(f);
byte[] buffer = new byte[4 * 1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
LOG.debug("streaming file contents @{}", bytesRead);
os.write(buffer, 0, bytesRead);
}
fis.close();
os.flush();
os.close();
}
};
return Response.ok(so, MediaType.TEXT_PLAIN).build();
} else {
return createNegativeXmlResponse("file not found or not readable: '"
+ f.getPath() + "'");
}
} catch (Exception e) {
return handle(e);
}
}
客户端(Junit 测试用例):
@Test
public void testDownloadFile() throws Exception {
Client client = ClientBuilder.newBuilder()
.register(MultiPartFeature.class).build();
WebTarget target = client.target(BASE_URI).path("/downloadFile/b.txt");
Response r = target.request(MediaType.TEXT_PLAIN_TYPE).get();
System.out.println(r.getStatus());
Object o = r.readEntity(StreamingOutput.class);
StreamingOutput so = (StreamingOutput) o;
}
服务器在 tomcat7 实例中运行。执行 r.readEntity 时我在客户端得到的是:
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=text/plain, type=interface javax.ws.rs.core.StreamingOutput, genericType=interface javax.ws.rs.core.StreamingOutput.
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:230)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:154)
...
如何从客户端的 Response 对象中获取 StreamingOutput 对象?
【问题讨论】: