Search code examples
restspring-bootresttemplate

How to get a generic map as a response from restTemplate exchange method?


We have a rest service that returns a byte array inside a map of type . While receiving the response if I use Map without the generics, the byte array data is converted to a String. Is it possible to send just the byte data from the server, if so how to retrieve that data from the client using RestTemplate?

 ResponseEntity<Map<String, byte[]>> result result = restTemplate.exchange("http://localhost:8085/api/fetchContent?Id=" + contentId+"&userName=trump", HttpMethod.GET, entity, Map.class, params);

The above code will give a compilation issue as the return type is a map.


Solution

  • Use ParameterizedTypeReference<T>:

    ParameterizedTypeReference<Map<String, byte[]>> responseType =
            new ParameterizedTypeReference<Map<String, byte[]>>() {};
    
    ResponseEntity<Map<String, byte[]>> responseEntity = 
            restTemplate.exchange("http://example.org", HttpMethod.GET, entity, responseType);