如何在Spring UriComponentsBuilder中编码逗号?

问题描述 投票:1回答:2

我有以下代码:

    String convertedBuilder = builder.toUriString();
    convertedBuilder = convertedBuilder.replace(",", "\\,");



    URI uri = UriComponentsBuilder.fromUriString(convertedBuilder)
              .build().toUri();

想法是用','(斜线和逗号)替换单个逗号'\,'。原始网址应该是这样的

'server-url'?name=te%5C%2Cst参数值'te\,st

但是Spring生成了这个:

'server-url'?name=te%5C%252Cst

我究竟做错了什么?

问候,

java spring spring-web
2个回答
1
投票

我有一个类似的要求,我必须用这样的GPS坐标调用服务:

http://example.com/path?param1=40.678806%2C-73.943244

UriComponentsBuilder独自会:

  • 不在参数值中编码,(逗号)
  • 编码逗号,如果我已经用URLEncoder编码参数,从而产生值40.678806%252C-73.943244

我解决了使用URLEncoder显式编码查询参数并告诉UriComponentsBuilder URL已经编码:

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://example.com/path")
        .queryParam("param1" , URLEncoder.encode("40.678806,-73.943244", "UTF-8"));

ResponseEntity<String> resp = template.exchange(
        builder.build(true).toUri(),
        HttpMethod.GET, 
        null, new ParameterizedTypeReference<String> () {}
    );

0
投票

如何在Spring UriComponentsBuilder中编码逗号?

UriComponentsBuilder不对逗号进行编码,因为RFC不要求对其进行编码。您必须按照Andreas在评论中的建议手动对其进行编码。

但是Spring会生成这个:'server-url'?name = te%5C%252Cst

不,它没有,正如安德烈亚斯所提到的那样。它编码反斜杠而不是逗号。如果您需要更多信息,请解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.