在开发中经常需要将字符串或url进行编码、解码,下面分别测试Java、JS、PHP中相关函数的应用。
Java
- 编码 URLEncoder.encode()
- 解码 URLDecoder.decode()
String s1="3 ?#:&(@!~-_.*')好a+/";
String s2="";
String s3="";
try {
s2 = URLEncoder.encode(s1, "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
s3=URLDecoder.decode(s2, "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
System.out.println("原字符串:" + s1);
System.out.println("编码:" + s2);
System.out.println("解码:" + s3);
运行结果:
原字符串:3 ?#:&(@!~-_.*')好a+/
编码:3+%3F%23%3A%26%28%40%21%7E-_.*%27%29%E5%A5%BDa%2B%2F
解码:3 ?#:&(@!~-_.*')好a+/
JS
- 编码 encodeURI()
- 解码 decodeURI()
let s1=encodeURI("3 ?#:&(@!~-_.*')好a+/");
let s2=decodeURI(s1);
console.log('编码', s1);
console.log('解码', s2);
运行结果:
编码 3%20?#:&(@!~-_.*')%E5%A5%BDa+/
解码 3 ?#:&(@!~-_.*')好a+/
- 编码 encodeURIComponent()
- 解码 decodeURIComponent()
let s1=encodeURIComponent("3 ?#:&(@!~-_.*')好a+/");
let s2=decodeURIComponent(s1);
console.log('编码', s1);
console.log('解码', s2);
运行结果:
编码 3%20%3F%23%3A%26(%40!~-_.*')%E5%A5%BDa%2B%2F
解码 3 ?#:&(@!~-_.*')好a+/
encodeURIComponent()函数不会对 ()-_.*~!’ 这些符号进行编码。
PHP
- 编码 urlencode()
- 解码 urldecode()
$s="3 ?#:&(@!~-_.*')好a+/";
$s2 = urlencode($s);
$s3 = urldecode($s2);
echo '编码:'.$s2.'<br/>';
echo '解码:'.$s3;
运行结果:
编码:3+%3F%23%3A%26%28%40%21%7E-_.%2A%27%29%E5%A5%BDa%2B%2F
解码:3 ?#:&(@!~-_.*')好a+/