简体   繁体   中英

Returning custom object with InputStream parameter in JAX-RS

I'm storing objects of type Binary in a database and I have a JAX-RS web service that can retrieve them by their ID.

public class Binary {
    private InputStream data;
    private String id;
    private String name;
    private String description;

    ... // constructors/getters/setters
}

I was able to get it working with this code:

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

I don't like wrapping the values in a FormDataMultiPart and unwrapping them in the client code. I want to directly return the Binary object like this:

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

    return binary;
}

I can't use XML or JSON representation because of the InputStream parameter. I'd appreciate any help of how to deal with this problem. Thanks!

If you have data as InputStream you will have problems having to reset every time you read from the InputStream. Better have it as byte[].

If you are using jackson you can then return like:

@GET
@Path("{id}")
@Produces(/* ? */)
public Response get(String documentId) {
    Binary binary = ... // get binary from database
    return Response.ok(binary).build();
}

you can test it with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM