RestTemplate GET请求请求参数

时间:2011-08-26 02:30:27

标签: parameters get request rest-client resttemplate

我必须调用REST Web服务,我计划使用RestTemplate。我查看了如何发出GET请求的示例,如下所示。

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

在我的情况下,RESTful网址如下所示。在这种情况下如何使用RestTemplate?

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

所以我的问题是如何发送GET请求的请求参数?

2 个答案:

答案 0 :(得分:32)

对于任何一种类型的网址,占位符的工作方式都相同,只需执行

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

或者更好的是,使用散列图进行实名匹配 -

答案 1 :(得分:0)

在向RESTful服务器发出请求时,在许多情况下,它需要发送查询参数,请求正文(在POSTPUT请求方法的情况下)以及请求到服务器。

在这种情况下,可以使用UriComponentsBuilder.build()构建URI字符串,根据需要使用UriComponents.encode()进行编码,并使用RestTemplate.exchange()发送URI,如下所示:

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;
}