URI编码解码

自实现

     private string UrlEncode(string str)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(Convert.ToString(byStr[i], 16));
            }
            return (sb.ToString());
        }
        private string UrlDecode(string str)
        {
            str = str.Replace(" ", "");
            if ((str.Length % 2) != 0)
                str += " ";
            byte[] returnBytes = new byte[str.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
            UTF8Encoding utf8 = new UTF8Encoding();
            string path = utf8.GetString(returnBytes);
            return path;
        }

.NET

string s= System.Web.HttpUtility.UrlEncode("123", System.Text.Encoding.Unicode); //编码
string b = System.Web.HttpUtility.UrlDecode(s, System.Text.Encoding.Unicode);  //解码

JS

encodeURI()

encodeURIComponent()

decodeURI()

decodeURIComponent()

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

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

winform程序对URL中的汉字进行编码

  我们通常会用到url的问号来向另一个页面传值,如果传递的值包含汉字,那就需要对汉字进行编码

  在asp.net中用下面的方法对汉字进行编码:

  引入System.Web命名空间

  System.Web.HttpContext.Current.Server.UrlEncode(“需要编码的汉字")

  在Winfrom程序中用下面的方法进行编码:

  同样引入System.Web命名空间

  编码:System.Web.HttpUtility.UrlEncode("需要编码的汉字", Encoding.GetEncoding("GB2312"))

  解码:System.Web.HttpUtility.UrlDecode(“需要编码的汉字", Encoding.GetEncoding("GB2312"))   

  在aspx中,一般无需解码,直接接用Request.QueryString接收即可。

原文地址:https://www.cnblogs.com/zhchsh/p/5455705.html