Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform an http request to another server from spring boot controller

How do I perform a GET HTTP request from my spring boot application hosted on localhost:8080 on a server hosted on localhost:80.

For example, how do I get an image hosted at locahost:80/image.jpg from my spring application?

like image 533
coman Avatar asked Feb 25 '26 03:02

coman


1 Answers

There are two ways you can make a third party external api request.

  1. RestTemplate

         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();
}
  1. Unirest Add unirest dependency in pom:
<!-- Unirest java -->
    <dependency>
      <groupId>com.mashape.unirest</groupId>
      <artifactId>unirest-java</artifactId>
      <version>${unirest.java.version}</version>
    </dependency>

Code to call api:

HttpResponse<JsonNode> jsonResponse = Unirest.get(your_get_url_in_string)
                    .header("header_string", "header_value")
                    .queryString("query", "query_if_any")
                    .asJson();
JsonNode responseBody = jsonResponse.getBody();
like image 143
Drashti Dobariya Avatar answered Feb 26 '26 15:02

Drashti Dobariya