Nonu
Nonu

Reputation: 15

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?

Upvotes: 1

Views: 12481

Answers (1)

jcompetence
jcompetence

Reputation: 8383

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);

Upvotes: 2

Related Questions