Home > Software engineering >  Spring RestTemplate to ping google
Spring RestTemplate to ping google

Time:07-12

How can I use spring restTemplate in java for a GET request to google.com or any other website? I tried like below but didn't work. Got error while extracting response for type [class java lang.String] and content type [text/html;charset=utf-8]

   ResponseEntity<String> response = null;
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
   MultiValueMap<String, Object> map = null;
    if(! method.matches("GET")) {
      objectMapper.enable(DeserilizationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
      map = objectMapper.convertValue(resource, LinkedMultiValueMap.class);
    }
    HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaType.ALL));
    messageConverters.add(converter);
    restTemplate.setMessageConverters(messageConverters);
    response = restTemplate.exchange("https://www.google.com", HttpMethod.GET, entity, String.class);

CodePudding user response:

From the snippet above seems that the problem arise from messageConverters, you are overwriting the whole default RestTemplate messageConverters causing it to fail.

List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
...
restTemplate.setMessageConverters(messageConverters);

Instead if you have a custom converter you should just:

restTemplate.getMessageConverters().add(converter)

MECE version, Just this should work:

final RestTemplate restTemplate = new RestTemplate();

@GetMapping("/test")
public ResponseEntity<String> test(){
    return restTemplate.exchange("https://www.google.com", HttpMethod.GET, null, String.class);
}
  • Related