Resttemplate: How to Send Url and Query Parameters Together

RestTemplate: How to send URL and query parameters together

I would use buildAndExpand from UriComponentsBuilder to pass all types of URI parameters.

For example:

String url = "http://test.com/solarSystem/planets/{planet}/moons/{moon}";

// URI (URL) parameters
Map<String, String> urlParams = new HashMap<>();
urlParams.put("planet", "Mars");
urlParams.put("moon", "Phobos");

// Query parameters
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
// Add query parameter
.queryParam("firstName", "Mark")
.queryParam("lastName", "Watney");

System.out.println(builder.buildAndExpand(urlParams).toUri());
/**
* Console output:
* http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney
*/

restTemplate.exchange(builder.buildAndExpand(urlParams).toUri() , HttpMethod.PUT,
requestEntity, class_p);

/**
* Log entry:
* org.springframework.web.client.RestTemplate Created PUT request for "http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney"
*/

How do I send a get request with path variables and query parameters using RestTemplate?

I fixed the problem using builder.buildAndExpand(carVariable).toUri()

The solution looks like this:

ResponseEntity<CarDetail> carDetails = restTemplate.exchange(
builder.buildAndExpand(carVariable).toUri(),
HttpMethod.GET,
requestEntity,
CarDetail.class);

Spring RestTemplate GET with parameters

OK, so I'm being an idiot and I'm confusing query parameters with url parameters. I was kinda hoping there would be a nicer way to populate my query parameters rather than an ugly concatenated String but there we are. It's simply a case of build the URL with the correct parameters. If you pass it as a String Spring will also take care of the encoding for you.

RestTemplate with Query params

Just pass them as part of the url string. Spring will do the rest, shown below are two types of parameter - an uri parameter and a request parameter:

String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings?example=stack",String.class,"42");

Docs here.

How to read query param value if special character (&) part of query param value

If the & character is part of the name or value in the query string then it has to be percent encoded. In the given example: contentName=abc%26def&path=Test&type=folder.



Related Topics



Leave a reply



Submit