我有以下代码:
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
我究竟做错了什么?
问候,
我有一个类似的要求,我必须用这样的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> () {}
);
如何在Spring UriComponentsBuilder中编码逗号?
UriComponentsBuilder不对逗号进行编码,因为RFC不要求对其进行编码。您必须按照Andreas在评论中的建议手动对其进行编码。
但是Spring会生成这个:'server-url'?name = te%5C%252Cst
不,它没有,正如安德烈亚斯所提到的那样。它编码反斜杠而不是逗号。如果您需要更多信息,请解决问题。