encodeURIComponent和URLEncoder.encode的区别

二者的区别:

1、 encodeURIComponent(str) :

  • 参数:str - 字符串;
  • js(前端)编码方法;
  • 对应的解码方法:decodeURIComponent(str);
  • 编码差异:
    1 ) 中文解码 时,中文编码必须是utf-8才能正常解码;
    2 ) !’()~对这个五个符号不进行编码
encodeURIComponent("!'()~");//!'()~

输出结果:
在这里插入图片描述

2、URLEncoder.encode(str,type) :

  • 参数:str - 字符串; type - 编码类型(UTF-8、GBK等);
  • Java(后端)编码方法,
  • 对应的解码方法:URLDecoder.decode(str,type)
  • 编码差异:
    1 ) 中文解码 时,可设置编码类型正常解码;
    2 ) !’()~ 对这个五个符号进行编码,与js的encodeURIComponent方法不同;
public static void main(String[] args) throws UnsupportedEncodingException {
   	 System.out.println(URLEncoder.encode("!'()~", "UTF-8"));//%21%27%28%29%7E
   }

输出结果:
在这里插入图片描述

二者的相似:

URLEncoder.encode编码类型为UTF-8时,与encodeURIComponent方法基本一致,但URLEncoder.encode方法会将空格编码为符号"+",而encodeURIComponent 则将空格编码为"%20’。

猜你喜欢

转载自blog.csdn.net/yihanzhi/article/details/85295049