在向 RESTful 服务器发出请求时,在许多情况下,它需要向服务器发送查询参数、请求正文(在请求方法的情况下)POST
以及PUT
请求中的标头。
在这种情况下,可以使用 UriComponentsBuilder.build() 构建 URI 字符串,如果需要使用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;
}