Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestTemplate with Query params

Tags:

java

rest

spring

I'm using org.springframework.web.client.resttemplate and I need to pass query params to my GET request.

Does anyone have any example of this?

like image 589
Nir Avatar asked Jun 17 '13 09:06

Nir


2 Answers

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.

like image 131
NimChimpsky Avatar answered Nov 02 '22 22:11

NimChimpsky


While making a request to a RESTful server, it requires in many a cases to send query parameters, request body (in case of POST and PUT request methods), as well as headers in the request to the server.

In such cases, the URI string can be built using UriComponentsBuilder.build(), encoded using UriComponents.encode() (useful when you want to send JSON or anything that has symbols { and } as part of the params), and sent using RestTemplate.exchange() like this:

public ResponseEntity<String> requestRestServerWithGetMethod()
{
    HttpEntity<?> entity = new HttpEntity<>(requestHeaders); // requestHeaders is of HttpHeaders type
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(rawValidUrl) // rawValidURl = http://example.com/hotels
            .queryParams(
                    (LinkedMultiValueMap<String, String>) allRequestParams); // The allRequestParams must have been built for all the query params
    UriComponents uriComponents = builder.build().encode(); // encode() is to ensure that characters like {, }, are preserved and not encoded. Skip if not needed.
    ResponseEntity<Object> responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.GET,
            entity, String.class);
    return responseEntity;
}

public ResponseEntity<String> requestRestServerWithPostMethod()
{
    HttpEntity<?> entity = new HttpEntity<>(requestBody, requestHeaders); // requestBody is of string type and requestHeaders is of type HttpHeaders
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(rawValidUrl) // rawValidURl = http://example.com/hotels
            .queryParams(
                    (LinkedMultiValueMap<String, String>) allRequestParams); // The allRequestParams must have been built for all the query params
    UriComponents uriComponents = builder.build().encode(); // encode() is to ensure that characters like {, }, are preserved and not encoded. Skip if not needed.
    ResponseEntity<Object> responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.POST,
            entity, String.class);
    return responseEntity;
}
like image 43
noob Avatar answered Nov 02 '22 22:11

noob