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

转载自:https://springboot.io/t/topic/1268

叙述

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 content = "Hello <springboot中文社区>";
		
		String result = URLEncoder.encode(content, "utf-8");
		System.out.println("URLEncoder编码:	" + result);
		
		result = UriUtils.encode(content, "utf-8");
		System.out.println("UriUtils编码:	" + result);
	}
}

输出结果

发布了22 篇原创文章 · 获赞 30 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/lizhengyu891231/article/details/103909190
今日推荐