使用RestTemplate发送带有请求参数的GET请求

12

我需要调用一个REST Web服务,打算使用RestTemplate。我查看了如何进行GET请求的示例,如下所示:

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

在我的情况下,RESTful URL 大致如下。如何在这种情况下使用 RestTemplate?

http://example.com/hotels?state=NY&country=USA

那么我的问题是如何发送GET请求的请求参数?

2个回答

35

占位符在任何类型的URL中都起作用,只需执行

 String result = restTemplate.getForObject("http://example.com/hotels?state={state}&country={country}", String.class,"NY","USA");

或者更好的做法是,使用哈希表进行实际名称匹配 -


1
在向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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接