在 JAX-RS 中返回带有 InputStream 参数的自定义对象

Returning custom object with InputStream parameter in JAX-RS

我将二进制类型的对象存储在数据库中,并且我有一个 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 中,然后在客户端代码中展开。我想像这样直接 return Binary 对象:

@GET
@Path("{id}")
@Produces(/* ? */)
Binary getBinary(@PathParam("id") String id) {
    Binary binary = ... // get binary from database

    return binary;
}

由于 InputStream 参数,我无法使用 XML 或 JSON 表示。 对于如何处理此问题的任何帮助,我将不胜感激。谢谢!

如果您将数据作为 InputStream,则每次从 InputStream 读取数据时都必须重新设置。最好把它写成 byte[].

如果您使用的是 jackson,那么您可以 return 喜欢:

@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();
}