RestTemplate with request parameters

I am using org.springframework.web.client.resttemplate and I need to pass the request parameters to my GET request.

Does anyone have an example of this?

+6
source share
2 answers

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

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

The docs are here.

+7
source

When executing a request to a RESTful server, in many cases it is necessary to send request parameters, request body (in the 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 constructed using UriComponentsBuilder.build () , encoded using UriComponents.encode () (useful when you want to send JSON or something that has the { and } characters as part of the parameters), and sent with 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; } 
0
source

Source: https://habr.com/ru/post/947447/


All Articles