Issue
i want to perform a get request on a server hosted on localhost:80 (for example but could be every host) from my spring boot application hosted on localhost:8080.
For example i want to get an image hosted on locahost:80/image.jpg from my spring application. How can i handle this?
Solution
You can use RestTemplate for that.
RestTemplate restTemplate = new RestTemplate();
String uri = localhost:80; // or any other uri
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity<?> result =
restTemplate.exchange(uri, HttpMethod.GET, entity, returnClass);
return result.getBody();
If you want to get images then use following method:
String url = "http://img.championat.com/news/big/l/c/ujejn-runi_1439911080563855663.jpg";
byte[] imageBytes = restTemplate.getForObject(url, byte[].class);
Files.write(Paths.get("image.jpg"), imageBytes);
You will also need to configure ByteArrayHttpMessageConverter in application config:
@Bean
public RestTemplate restTemplate(List<HttpMessageConverter<?>> messageConverters) {
return new RestTemplate(messageConverters);
}
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
return new ByteArrayHttpMessageConverter();
}
Answered By - Drashti Dobariya
Answer Checked By - David Goodson (JavaFixing Volunteer)