解决JDK URLEncoder.encode 编码空格变 + 号

发布时间 2023-11-04 11:48:18作者: coolw

JDK URLEncoder.encode

jdk自带的URL编码工具类 URLEncoder, 在对字符串进行URI编码的时候,会把空格编码为 + 号。
空格的URI编码是:%20

解决方案:可以对编码后的字符串进行 + 替换成 %20,但这种解决方案并不优雅
另外字符串中的 + 会 encode 成 %2B
  • 使用jdk提供的 URLEncoder 工具类
/**
 * 使用 JDK 提供的 URLEncoder 工具类进行编码
 */
@Test
public void testJdkEncode() throws UnsupportedEncodingException {
	String val = "111 222+333  ";

	// 编码
	String encode = URLEncoder.encode(val, "utf-8");
	System.out.println("encode:" + encode);

	String rst = encode.replaceAll("\\+", "%20");
	System.out.println("rst:" + rst);
}

推荐使用

日常对于数据进行AES加密后进行base64的场景,可能会造成AES解密失败
  • 1.使用spring提供的 UriUtils 工具类
/**
 * 使用 Spring 提供的 UriUtils 工具类进行编码和解码
 */
@Test
public void testSrpingEncode() {
    String val = "111 222+333";

	// 编码
	String encode = UriUtils.encode(val, "utf-8");
	System.out.println("encode:" + encode);

	// 解码
	String decode = UriUtils.decode(encode, "utf-8");
	System.out.println("decode:" + decode);

	System.out.println(Objects.equals(val, decode));
}

  • 2.使用hutool提供的 URLUtil 工具类
/**
 * 使用 Hutool 提供的 UriUtils 工具类进行编码和解码
 */
@Test
public void testHutoolEncode() {
    String val = "111 222+333";

	// 编码
    String encode = URLUtil.encodeAll(val);
	System.out.println("encode:" + encode);

	// 解码
	String decode = URLUtil.decode(encode);
	System.out.println("decode:" + decode);

	System.out.println(Objects.equals(val, decode));
}