javascript 与 c# 的网址编码

来源:互联网 发布:共享windows无法访问 编辑:程序博客网 时间:2024/05/16 19:54

javascript的编码方式:

escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z (已经不推介使用)

encodeURI不编码字符有82个:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z

encodeURIComponent不编码字符有71个:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z

1.JS: escape :
js使用数据时可以使用escape
例如:搜藏中history纪录。
0-255以外的unicode值进行编码时输出%u****格式,其它情况下escape,encodeURI,encodeURIComponent编码结果相同。
2.JS: encodeURI :
进行url跳转时可以整体使用encodeURI
例如:Location.href=encodeURI("http://cang.baidu.com/do/s?word=百度&ct=21");
3.JS: encodeURIComponent :
传递参数时需要使用encodeURIComponent,这样组合的url才不会被#等特殊字符截断。                           
例如:<script language="javascript">document.write('<a href="http://passport.baidu.com/?logout&aid=7& u='+encodeURIComponent("http://cang.baidu.com/bruce42")
+'">退出</a& gt;');</script>


C#中编码主要方法:
1.Server.UrlEncode && HttpUtility.UrlEncode:不推荐
 把这两个放到一起说是因为这两个方法在绝大多数情况下是一样的。它们的区别是HttpUtility.UrlEncode默认使用UTF8格式编码,而Server.UrlEncode是使用系统预设格式编码,Server.UrlEncode使用系統预设编码做为参数调用HttpUtility.UrlEncode编码,所以如果系统全局都用UTF8格式编码,这两个方法就是一样的。
    这两个方法是怎么编码的呢,我们来看个示例:
string url1 = "http://www.cnblogs.com/a file with 
spaces.html?a=1&b=博客园#abc";
Response.Write(HttpUtility.UrlEncode(url1) );
//output
http%3a%2f%2fwww.cnblogs.com%2fa+file+with+spaces.html%3fa%3d1%26b%3d%e5%8d%9a%e5%ae%a2%e5%9b%ad%23abc
由上面的例子我们可以看出,HttpUtility.UrlEncode对冒号(:)和斜杠(/)进行了编码,所以不能用来对网址进行编码。
所以不推荐用这两个方法对URI进行编码。

2.Uri.EscapeUriString:用于对网址编码(不包含参数)
string url1 = "http://www.cnblogs.com/a file with spaces.html?a=1&b=博客园#abc";
Response.Write( Uri.EscapeUriString(url1));
//outputs:
http://www.cnblogs.com/a%20file%20with%20spaces.html?a=1&b=%E5%8D%9A%E5%AE%A2%E5%9B%AD#abc
可以看出,Uri.EscapeUriString对空格进行了编码,也对中文进行了编码,但对冒号(:)、斜杠(/)和井号(#)未编码,所以此方法可以用于网址进行编码,但不能对参数进行编码,作用类似JavaScript中的encodeURI方法


Uri.EscapeDataString:用于对网址参数进行编码
string url1 = "http://www.cnblogs.com/a file with spaces.html?a=1&b=博客园#abc";
Response.Write(Uri.EscapeDataString(url1));
//outputs:
http%3A%2F%2Fwww.cnblogs.com%2Fa%20file%20with%20spaces.html%3Fa%3D1%26b%3D%E5%8D%9A%E5%AE%A2%E5%9B%AD%23abc
可以看出,Uri.EscapeDataString对冒号(:)、斜杠(/)、空格、中文、井号(#)都进行了编码,所以此方法不可以用于网址进行编码,但可以用于对参数进行编码,作用类似JavaScript中的encodeURIComponent方法

原创粉丝点击