关于C# UrlDecode 同时解码UTF-8和GB2312
由于特殊要求,需要对URL进行解码,由于不能确定URL是BG2312还是UTF-8,所以用下面的方法来完成,不知道能否完全胜任,大家来帮我测试一下,同时也希望有人能提供更好的方法来完成URL解码。
private static bool CheckIsUTF8(string url)
{
//将URL转成UTF-8字节数组
byte[] bs = Encoding.GetEncoding("UTF-8").GetBytes(url);
for (int i = 0; i < bs.Length; i++)
{
//查找字节239 191 189,如果找到退出循环,标记为GB2312
if (bs[i++] == 239 && bs[i] == 191)
return false;
}
return true;
}
public static string URLDecode(string strUrl)
{
//将URL转为小写
string lowerUrl = strUrl.ToLower();
//判断URL中是否包含%,如果不包含%就不需要解码
if (lowerUrl.IndexOf('%') != -1)
{
//判断URL中是否包含%E,如果不包含直接用GB2312解码
if (lowerUrl.IndexOf("%e") != -1)
{
//以UTF-8对URL进行解码
string stringUrl = System.Web.HttpUtility.UrlDecode(strUrl, Encoding.GetEncoding("UTF-8"));
//判断解码后的字符串是否为UTF-8编码
if (CheckIsUTF8(stringUrl))
return stringUrl;
else
return System.Web.HttpUtility.UrlDecode(strUrl, Encoding.GetEncoding("GB2312"));
}
return System.Web.HttpUtility.UrlDecode(strUrl, Encoding.GetEncoding("GB2312"));
}
return strUrl;
}