C#URL编码解码演示代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            jiema();
            //bianma();
        }

      public static void jiema()
        {
            string oStr = "http://www.baidu.com/s?bs=%D6%D0%B9%FA&f=8&wd=%D6%D0%B9%FA";
            //oStr是UrlEncode编码字符串
            Encoding gb2312 = Encoding.GetEncoding("gb2312");
            Encoding utf8 = Encoding.UTF8;
            //首先用utf-8进行解码
            string key = HttpUtility.UrlDecode(oStr, utf8);
            // 将已经解码的字符再次进行编码.
            string encode = HttpUtility.UrlEncode(key, utf8).ToLower();
            //与原来编码进行对比,如果不一致说明解码未正确,用gb2312进行解码
            if (oStr != encode)
                key = HttpUtility.UrlDecode(oStr, gb2312);

            Console.WriteLine(key);
            Console.ReadKey();
        }

      public static void bianma()
      {
          string oStr = "聚合";
          //oStr是UrlEncode编码字符串
          Encoding gb2312 = Encoding.GetEncoding("gb2312");
          string m = System.Web.HttpUtility.UrlEncode(oStr, gb2312);

          Console.WriteLine(m);
          Console.ReadKey();
      }
    }
}

posted @ 2010-02-15 12:56  猪悟能  阅读(712)  评论(0编辑  收藏  举报