14

I am fetching the byte array using spring framework rest template, But I also need to fetch the Mediatype of this byte .

The mediaType of this bytearray can be of any type.

The code used now for fetching byte is below.

   HttpHeaders headers = new HttpHeaders();
   headers.setAccept(Collections.singletonList(MediaType.valueOf("application/pdf")));
   ResponseEntity<byte[]> result = restTemp.exchange(url, HttpMethod.GET, entity, byte[].class,documentId);

The above code will fetch only pdf content type.

How to set the contentType to accept any generic MediaType because the service at the other end is providing any random MediaType for the byteArray.

Could someone please suggest how the MediaType can be fetched.

Any suggestions are welcome..

Tiny
  • 683
  • 5
  • 18
  • 36

4 Answers4

19

Just not send the accept header to not force the server to return that content-type. This is the same as sending a wildcard */*

//HttpHeaders headers = new HttpHeaders();
//headers.setAccept(Collections.singletonList(MediaType.WILDCARD));
ResponseEntity<byte[]> result = restTemp.exchange(url, HttpMethod.GET, entity, byte[].class,documentId);

After this, extract the content-type from the headers of the response

 byte body[] = result.getBody();
 MediaType contentType = result.getHeaders().getContentType();
pedrofb
  • 37,271
  • 5
  • 94
  • 142
1

You can set the MediaType as application/octet-stream , look at here

Community
  • 1
  • 1
Vasu
  • 21,832
  • 11
  • 51
  • 67
0

You can store a media type in the HTTP headers and use - ResponseEntity.getHeaders(), for instance. or you can wrap byte array and media type into holder class.

toootooo
  • 196
  • 7
  • Thanks for the Response. Yes this will give me MediaType but only the one set in acceptHeader.. But the bytearray can be anything like a pdf or jpg or png or txt file .. – Tiny Nov 04 '16 at 16:28
0

MediaType mediaType = result.getHeaders().getContentType();

Andy W
  • 380
  • 1
  • 5
  • 13
  • Hi Andy, Thanks for the Response. Yes this will give me MediaType but only the one set in acceptHeader.. But the bytearray can be anything like a pdf or jpg or png or txt file .. – Tiny Nov 04 '16 at 16:27
  • It's not the one set in the accept header, it's set by the server when it creates the response. If the server sets the MediaType based on what the byte array represents (e.g. application/pdf for a pdf file), then you can use the Content-Type header as such. – Andy W Nov 04 '16 at 16:40