java构建http请求链接时,参数中加号“+”被转为空格的问题
在Java中使用Spring的UriComponentsBuilder构建URI时,加号(+)会被默认编码为空格,这是因为URL编码规范中加号代表空格。为确保加号被正确编码为%2B,需要显式启用全编码模式。
这是历史原因,在HTML 4.01规范中规定了:当content-type为application/x-www-form-urlencoded时,对names和vaules进行转义,空格用'+'代替
。
以下是解决方案:
String param = "ab+c"; // 示例
String uriString = UriComponentsBuilder
.fromHttpUrl("http://x.x.x.x:xxxx/api/xxx")
.queryParam("param", param)
.encode(StandardCharsets.UTF_8)
.toUriString();
String url = uriString.replace("+", "%2B");
也可以在服务器端将获取参数的方法由reuqest.getParameter改为request.getQueryString(),然后对得到的字符串进行解析。