我正在使用 org.springframework.web.client.resttemplate ,我需要将查询参数传递给我的 GET 请求。
有没有人有这方面的例子?
只需将它们作为 url 字符串的一部分传递。Spring 将完成剩下的工作,下面显示了两种类型的参数 - uri 参数和请求参数:
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings?example=stack",String.class,"42");
在向 RESTful 服务器发出请求时,在许多情况下,它需要向服务器发送查询参数、请求正文(在请求方法的情况下)POST
以及PUT
请求中的标头。
在这种情况下,可以使用 UriComponentsBuilder.build() 构建 URI 字符串,使用UriComponents.encode ()进行编码(当您想要发送 JSON 或任何具有符号并作为参数一部分的东西时很有用),并使用RestTemplate 发送。像这样的交换():{
}
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;
}