При отправке запроса на сервер RESTful во многих случаях требуется отправка параметров запроса, тела запроса (в случае POST
и PUT
методов запроса), а также заголовков в запросе на сервер..
В таких случаях строку URI можно построить с помощью UriComponentsBuilder.build () , закодировать с помощью UriComponents.encode () , если необходимо, и отправить с использованием RestTemplate.exchange () как это:
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;
}