Srishti
Srishti

Reputation: 355

Is it possible to send two different Content-Type for downloading file using jax-rs POST method

Is it possible to send two different Content-Type for POST method using post-man? Like, if the service is used for downloading excel file so in that case, @Consumes(MediaType.APPLICATION_JSON) is used for sending some user detail which is json structure and @Produces(MediaType.APPLICATION_OCTET_STREAM) is used for sending back the response as file. NOTE: I don't want to use form-data, that is a constraint for this service.

Upvotes: 0

Views: 665

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208974

On the client request, the Content-Type header is only for the type of data that is in the entity body. The Accept header is what you send for the type of data you want back.

On the server side, it is perfectly fine to do the following.

@POST
@Path("something")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response post(Model model) throws Exception {
    final InputStream in = new FileInputStream("path-to-file");
    StreamingOutput entity = new StreamingOutput() {
        @Override
        public void write(OutputStream out) {
            IOUtils.copy(in, out);
            out.flush();
        }
    };
    return Response.ok(entity)
            .header(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment;filename=somefile.xls")
            .build();
}

The request to this endpoint should look like

POST /api/something HTTP 1.1
Content-Type: application/json;charset=utf-8
Accept: application/octet-stream

{"the":"json", "entity":"body"}

See also:

  • This post about purpose of @Produces and @Consumes and the role they play in content negotiation.

Aside

As an aside, consider using application/vnd.ms-excel as the Content-Type instead of application/octet-stream. This is already the standard MIME type for Microsoft Excel files1. When using StreamingOutput as the response entity type, you can make the @Produces anything you want, as there is no real conversion needed.

In Postman, when you use the "Send and download" feature, you will notice that when the Content-Type is application/octet-stream, it will suggest the file extension of .bin when saving the file. But if you have the Content-Type as application/vnd.ms-excel, then the suggested extension is .xls, which is what it should be.


1. Incomplete list of MIME types

Upvotes: 1

Related Questions