【问题标题】:Returning custom object with InputStream parameter in JAX-RS在 JAX-RS 中返回带有 InputStream 参数的自定义对象
【发布时间】:2018-02-20 22:12:32
【问题描述】:

我将二进制类型的对象存储在数据库中,并且我有一个 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 表示。 我将不胜感激有关如何处理此问题的任何帮助。谢谢!

【问题讨论】:

    标签: java jax-rs inputstream


    【解决方案1】:

    如果您有数据作为 InputStream,那么每次从 InputStream 读取数据时都会遇到问题。最好把它写成 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 2012-06-16
      • 2013-06-09
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-03-14
      相关资源
      最近更新 更多