Explain Codes LogoExplain Codes Logo

Spring RestTemplate GET with parameters

java
rest-template
http-requests
uri-components
Alex KataevbyAlex Kataev·Sep 17, 2024
TLDR

Let's do a GET request with RestTemplate and send parameters using UriComponentsBuilder:

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://example.com/api/resource") .queryParam("param1", "value1") .queryParam("param2", "value2"); String result = new RestTemplate().getForObject(builder.toUriString(), String.class);

You've now done a GET to http://example.com/api/resource?param1=value1&param2=value2, and auto-encoded the parameters like a boss.

To tote along some custom headers, create an HttpHeaders instance, sprint over to HttpEntity, and finally fire off the request with restTemplate.exchange():

HttpHeaders headers = new HttpHeaders(); headers.set("CoolBeans", "123Beans"); HttpEntity<String> entity = new HttpEntity<>(headers); // Knock-knock, anybody home? ResponseEntity<String> response = new RestTemplate().exchange( builder.toUriString(), HttpMethod.GET, entity, String.class);

Clear tactics with requests

Tailoring your requests is like making a smoothie – gather your ingredients and blend away:

GET-ing down with dynamic parameters

To handle dynamic parameters like a pro, simply chain additional calls to .queryParam(). Imagine you have a magic flute blowing out parameters:

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl); if (magicFlutePlaying) { builder.queryParam("melody", fluteMelody); } // Play on... String uri = builder.toUriString();

POST with a serving of JSON body and parameters

For POST requests where you're sending a JSON body alongside URL parameters, you'd have to assemble things like a master LEGO builder:

HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<YourMasterpiece> requestEntity = new HttpEntity<>(yourMasterpiece, headers); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(legoBaseUrl) .queryParam("instructions", "123"); URI uri = builder.build().toUri(); // As easy as building a spaceship 🚀 ResponseEntity<String> response = restTemplate.exchange( uri, HttpMethod.POST, requestEntity, String.class);

Handling peculiar cases

Because we live in a world where not everything is unicorns and rainbows 🌈. Here's how you deal with peculiar scenarios:

Path variables vs query parameters

It's like corn flakes or oatmeal for breakfast. Path variables and query parameters both have their own place and time.

// Path variable String uri = "http://example.com/users/{userId}"; // Query parameter UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri) .queryParam("detail", "astonishingFeatures");

Variable expansion

Expand variables correctly, because nobody likes a surprise pop-serving from a jack-in-the-box:

UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl("http://example.com/users/{userId}") .buildAndExpand("42"); String uri = uriComponents.toUriString(); // Result: "http://example.com/users/42"

Guide to best practices

Lean & mean tactics to becoming a RestTemplate professional:

Immutable URIs

Stick to UriComponents whenever possible for your URIs. Thread-safety and predictability are worth it!

Exception handling

Exception handling isn't an option—it's a requirement. Network issues and server tantrums can happen.

Flexible HttpEntity

Embrace the power of HttpEntity. Used right, it can represent both request and response, giving you more flexibility with your HTTP methods.