我将 Binary 类型的对象存储在数据库中,并且我有一个 JAX-RS Web 服务,可以通过它们的 ID 检索它们。
public class Binary {
private InputStream data;
private String id;
private String name;
private String description;
... // constructors/getters/setters
}
我能够使用以下代码让它工作:
@GET
@Path("{id}")
@Produces(MediaType.MULTIPART_FORM_DATA)
Response getBinary(@PathParam("id") String id) {
Binary binary = ... // get binary from database
FormDataMultiPart multipart = new FormDataMultiPart();
multipart.field("name", binary.getName());
multipart.field("description", binary.getDescription());
multipart.field("data", app.getData(),
MediaType.APPLICATION_OCTET_STREAM_TYPE);
return multipart;
}
我不喜欢将值包装在 FormDataMultiPart 中并在客户端代码中解开它们。我想像这样直接返回 Binary 对象:
@GET
@Path("{id}")
@Produces(/* ? */)
Binary getBinary(@PathParam("id") String id) {
Binary binary = ... // get binary from database
return binary;
}
由于 InputStream 参数,我无法使用 XML 或 JSON 表示形式。 对于如何处理这个问题的任何帮助,我将不胜感激。谢谢!
最佳答案
如果您将数据作为输入流,那么每次从输入流读取数据时,您都会遇到必须重置的问题。最好将其作为 byte[]。
如果您使用 Jackson,则可以返回如下:
@GET
@Path("{id}")
@Produces(/* ? */)
public Response get(String documentId) {
Binary binary = ... // get binary from database
return Response.ok(binary).build();
}
您可以使用以下方法进行测试:
CloseableHttpClient httpclient = HttpClients.createDefault();
ObjectMapper mapper = new ObjectMapper();
TestObj obj = new TestObj();
obj.setFile(IOUtils.toByteArray(new FileInputStream(new File("C:\\download.jpg"))));
obj.setMimetype("image/jpeg");
obj.setDescription("asd");
String jsonInString = mapper.writeValueAsString(obj);
HttpPost httpPost = new HttpPost("http://localhost:8080/url");
httpPost.setHeader("Authorization", "Bearer asdf");
httpPost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(jsonInString);
httpPost.setEntity(se);
System.out.println(httpPost.toString());
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println("!!!! " + jsonInString);
System.out.println("!!!! " + se.toString());
System.out.println("!!!! " + response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
EntityUtils.consume(entity2);
} finally {
response2.close();
}
关于java - 在 JAX-RS 中返回带有 InputStream 参数的自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46176538/