修复HttpUtil.normalizeParams 在极端输入下抛 StringIndexOutOfBoundsException(pr#4216@Github)

This commit is contained in:
Looly
2026-01-18 18:50:40 +08:00
parent 59c596bbe4
commit 3552ccf399
2 changed files with 13 additions and 3 deletions

View File

@@ -18,6 +18,7 @@ package cn.hutool.v7.core.net.url;
import cn.hutool.v7.core.convert.ConvertUtil;
import cn.hutool.v7.core.map.MapUtil;
import cn.hutool.v7.core.text.CharUtil;
import cn.hutool.v7.core.text.StrUtil;
import cn.hutool.v7.core.util.CharsetUtil;
@@ -178,9 +179,12 @@ public class UrlQueryUtil {
}
// 以&结尾则去除之
final int lastIndex = builder.length() - 1;
if ('&' == builder.charAt(lastIndex)) {
builder.delete(lastIndex, builder.length());
if (!builder.isEmpty()) {
final int lastIndex = builder.length() - 1;
if (CharUtil.AMP == builder.charAt(lastIndex)) {
//builder.delete(lastIndex, builder.length());
builder.deleteCharAt(lastIndex);
}
}
return builder.toString();
}

View File

@@ -166,4 +166,10 @@ public class UrlQueryUtilTest {
final String encodeResult = UrlQueryUtil.normalizeQuery("", CharsetUtil.UTF_8);
Assertions.assertEquals("", encodeResult);
}
@Test
void normalizeQueryEndWithAmpersand(){
final String encodeResult = UrlQueryUtil.normalizeQuery("参数&", CharsetUtil.UTF_8);
Assertions.assertEquals("%E5%8F%82%E6%95%B0=", encodeResult);
}
}