jdk自带的URL编码工具类 URLEncoder 在对字符串进行URI编码的时候,会把空格编码为 + 号。
空格的URI编码其实是:%20
解决办法:对编码后的字符串,进行 + 号替换为 %20。
使用spring提供的 UriUtils 来代替URLEncoder进行编码
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.springframework.web.util.UriUtils;
public class MainTest {
public static void main(String[] args) throws UnsupportedEncodingException {
String encode = URLEncoder.encode("2023-04-13 00:00:00", "UTF-8");
String decode = URLDecoder.decode("2023-04-13%2000%3A00%3A00", "UTF-8");
String springEncode = UriUtils.encode("2023-04-13 00:00:00", "utf-8");
String springDecode = UriUtils.decode("2023-04-13%2000%3A00%3A00", "utf-8");
System.out.println("encode = " + encode);
System.out.println("decode = " + decode);
System.out.println("springEncode = " + springEncode);
System.out.println("springDecode = " + springDecode);
}
}
结果:
encode = 2023-04-13+00%3A00%3A00
decode = 2023-04-13 00:00:00
springEncode = 2023-04-13%2000%3A00%3A00
springDecode = 2023-04-13 00:00:00