字符串解码

URL编码解码(转义/反转义)

 

步骤:

1.url中含%3A%2F%2F一类的字符串,需要转码HttpUtility.UrlDecode(bookingUrl,Encoding.UTF8)

2.通过网络传输 字符串中的&被转义成了&amp ; 需要将相应的&amp ; 转换回&。

案例:

1)原url:
var sourceUrl="http://www.mafengwo.cn/hotel/booking/go2booking.php?from=hotel_new&mddid=10195&poi_id=15702870&to=youyu_pkg&j=http%3A%2F%2Fwww.mafengwo.cn%2Fhotel_zx%2Fhotel%2Findex.php%3FiId%3D1388617%26sRoom%3D2";

2)HttpUtility.UrlDecode(bookingUrl,Encoding.UTF8) 后得到结果:
var decodeUrl=HttpUtility.UrlDecode(bookingUrl,Encoding.UTF8);

decodeUrl的值为:

http://www.mafengwo.cn/hotel/booking/go2booking.php?from=hotel_new&mddid=10195&poi_id=15702870&to=youyu_pkg&j=http://www.mafengwo.cn/hotel_zx/hotel/index.php?iId=1388617&sRoom=2

3)自己编写一个HtmlDecode的方法,将&amp ;转换回&

decodeUrl=decodeUrl.HtmlDecode();

decodeUrl的值为:

http://www.mafengwo.cn/hotel/booking/go2booking.php?from=hotel_new&mddid=10195&poi_id=15702870&to=youyu_pkg&j=http://www.mafengwo.cn/hotel_zx/hotel/index.php?iId=1388617&sRoom=2

 

public static class HtmlExtension
    {
        /// <summary>
        /// 编码-转义
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string HtmlEncode(this string str)
        {
            if (str.Length == 0)
            {
                return str;
            }
            str = str.Replace("<","&lt;");
            str = str.Replace(">","&gt;");
            str = str.Replace("&","&amp;");
            str = str.Replace("'","&#39;");
            str = str.Replace(" ","&nbsp;");
            str = str.Replace("\"","&quot;");
            str = str.Replace("\n","<br />");
            return str;
        }
        /// <summary>
        /// 解码-反转义
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string HtmlDecode(this string str)
        {            
            if (str.Length == 0)
            {
                return str;
            }
            str = str.Replace("&lt;", "<");
            str = str.Replace("&gt;", ">");
            str = str.Replace("&amp;", "&");
            str = str.Replace("&#39;", "'");
            str = str.Replace("&nbsp;", " ");
            str = str.Replace("&quot;", "\"");            
            str = str.Replace("<br />", "\n");
            return str;            
        }
    }

 

posted @ 2019-04-28 10:07  yoyo2019  阅读(209)  评论(0编辑  收藏  举报