Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring REST Template for Byte

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..

like image 646
Tiny Avatar asked Nov 04 '16 16:11

Tiny


People also ask

How do you send a byte array in RestTemplate?

Show activity on this post. MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>(); parts. add("field 1", "value 1"); parts. add("file", new ClassPathResource("myFile.

What is RestTemplate postForObject?

RestTemplate's postForObject method creates a new resource by posting an object to the given URI template. It returns the result as automatically converted to the type specified in the responseType parameter.

What is RestTemplate getForObject?

The getForObject method fetches the data for the given response type from the given URI or URL template using HTTP GET method. To fetch data for the given key properties from URL template we can pass Object Varargs and Map to getForObject method. The getForObject returns directly the object of given response type.

Is RestTemplate deprecated?

RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it's not really that future proof.


1 Answers

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();
like image 141
pedrofb Avatar answered Oct 20 '22 01:10

pedrofb