如何使用Spring RestTemplate将安培数作为参数值的一部分传递



我正在从一个Web服务向另一个Web Service发出GET请求,我需要传递一个值中包含"与"的参数。例如CCD_ 2,其中CCD_;J.然而,使用Spring的RestTemplate执行此操作似乎是不可能的。

当我通过cURL进行此调用时,我只需将"与"符号替换为%26,即flavor=PB%26J

然而,当我将URL传递给Spring的RestTemplate.exchange(String, HttpMethod, HttpEntity<?>, Class<T>)时,它似乎选择性地转义了字符。也就是说,如果我传入flavor=PB%26J,它将转义百分比符号,从而生成flavor=PB%2526J。但是,如果我传入flavor=PB&J,它将保留"与"符号,从而生成flavor=PB&J,它被视为两个参数。

我已经追踪到RestTemplate调用UriTemplateHandler.expand(String, Object...)的位置,但我不确定从这里我能做什么,因为我开始使用的输入值都不会导致所需的PB%26J

您可以在UriComponentsBuilder的帮助下生成url字符串。encode()方法应该可以帮助您正确地对url进行编码。

String url = UriComponentsBuilder
.fromUriString("http://sandwich.com")
.queryParam("flavor", "PB&J")
.encode() // this should help with encoding the url properly
.build().toString(); // Gives http://sandwich.com?flavor=PB%26J
RestTemplate.exchange(url, HttpMethod, HttpEntity<?>, Class<T>)

或者更好的是,只传递URI对象,而不是

URI uri = UriComponentsBuilder
.fromUriString("http://sandwich.com")
.queryParam("flavor", "PB&J")
.encode() // this should help with encoding the url properly
.build();
RestTemplate.exchange(uri, HttpMethod, HttpEntity<?>, Class<T>)

在您的情况下,这应该有效:

@GetMapping("/")
public List<Entity> list(@PathParam("flavor") String[] values) throws Exception {

最新更新