How to accept bytes in REST API?

The client sends bytes, and not always different JSON objects. The question is what should be written in the @Produces annotations, @Consumes and in the parameters (it is necessary that he also send different JSON objects)?

  • Judging by the instructions on the annotations you are using as a framework. Which one - Dmitriy Simushev
  • 2
    Not quite clear the problem that confronted you! What does it mean not always different, but should? What is @Produces @Produces , @Consumes can it be from the world of PHP ? In other words, formulate your task more precisely - sys_dev

1 answer 1

Judging by the annotations and your usual questions, it's about JAX-RS.

Use the @Produces for the byte stream in @Produces and MediaType.APPLICATION_OCTET_STREAM .


To receive from a client in a method, use an InputStream parameter.

 @POST @Consumes(MediaType.APPLICATION_OCTET_STREAM) public Response getData(InputStream inputStream) { // вычитывайте данные из inputStream return Response.ok().build(); } 

To return to the client bytes:

  • Give the entire byte array if the data is available in advance and fit into memory:

     @GET @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response getData() { byte[] data = ... ; return Response.ok(data).build(); } 
  • either use StreamingOutput

     @GET @Produces(MediaType.APPLICATION_OCTET_STREAM) public StreamingOutput getData() { return new StreamingOutput() { public void write(final OutputStream outputStream) { // здесь пишите ваши данные в поток outputStream } }; }