首页 文章

RestTemplate GET请求请求参数

提问于
浏览
11

我必须调用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 回答

  • 31

    对于任何类型的url,占位符的工作方式都相同

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

    或者更好的是,使用哈希映射进行实名匹配 -

  • 0

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

    在这种情况下,可以使用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;
    }
    

相关问题