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

叙述

jdk自带的URL编码工具类 URLEncoder 在对字符串进行URI编码的时候,会把空格编码为 + 号。
空格的URI编码其实是:%20
搜素引擎上不少人都遇到这个问题,哀声一片。
解决办法大都是对编码后的字符串,进行 + 号替换为 %20。总感觉这种方式不优雅。

解决方案

使用spring提供的 UriUtils 来代替URLEncoder进行编码

 
  1. import java.io.UnsupportedEncodingException;
  2. import java.net.URLEncoder;
  3.  
  4. import org.springframework.web.util.UriUtils;
  5.  
  6. public class MainTest {
  7. public static void main(String[] args) throws UnsupportedEncodingException {
  8. String content = "Hello <springboot中文社区>";
  9.  
  10. String result = URLEncoder.encode(content, "utf-8");
  11. System.out.println("URLEncoder编码: " + result);
  12.  
  13. result = UriUtils.encode(content, "utf-8");
  14. System.out.println("UriUtils编码: " + result);
  15. }
  16. }
 
java
 

输出结果

 
    1. URLEncoder编码:Hello+%3Cspringboot%E4%B8%AD%E6%96%87%E7%A4%BE%E5%8C%BA%3E
    2. UriUtils编码:Hello%20%3Cspringboot%E4%B8%AD%E6%96%87%E7%A4%BE%E5%8C%BA%3E
  1.  
 
posted @ 2026-05-06 14:59  charyGao  阅读(31)  评论(0)    收藏  举报