简体   繁体   中英

Spring RestTemplate not working

I have created application in Spring using RestTemplate, Using Rest-Template I am consuming an external webservice which is having a header as Accept as "application/json". In my Rest-Template I have added the header but still it is giveing me the following exception

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.site.Employee] and content type [application/octet-stream]

My code is as given below

    private static String BASE_URI = "http://localhost:8181/test/employee"

    final HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
    requestHeaders.setContentType(new MediaType("application", "json"));
    final HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

    final RestTemplate restTemplate = new RestTemplate();

    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    final ResponseEntity<Employee> responseEntity = restTemplate.exchange(BASE_URI, HttpMethod.GET, requestEntity, Employee.class);

Can anyone please tell me some solution for this

Update 1

When I tries the below code, it is working fine

final ResponseEntity<String> responseEntity = restTemplate.exchange(BASE_URI, HttpMethod.GET, requestEntity, String.class);
Employee employee = new ObjectMapper().readValue(responseEntity.getBody(), Employee.class);

You'll need to add application/octet-stream to the list of supported mimetypes in MappingJackson2HttpMessageConverter :

final MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM