Search code examples
javaspring-bootrestmicroservices

Spring Boot - How to send a POST request via a url with query parameters and store the response inside a method?


I have a url generated by a GET method which is somewhat of this format:

https://service-name/api?param1=<value1>&param2=<value2>&param3=<value3>.....

I need to hit this url and store the response (which will be of type application/x-www-form-urlencoded) into a variable, which will be used further.

The issue is that it needs to be done inside the method (get the url and pass it to get a response).

How to go about it?


Solution

  • For a spring boot application to consume an external API, you can use RestTemplate.

    An example of usage is below. The response you receive is of type String.

    RestTemplate restTemplate = new RestTemplate();
    
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.add("Header", "header1");
    
    
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://foo/api/v3/projects/1/labels")
            .queryParam("param1", param1)
            .queryParam("param2", param2);
    
    HttpEntity<?> entity = new HttpEntity<>(headers);
    
    HttpEntity<String> response = restTemplate.exchange(
            builder.toUriString(), 
            HttpMethod.GET, 
            entity, 
            String.class);