url的关键字不知道是uft-8还是GBK

本文提供了一种解决URL中未进行encode的汉字乱码问题的方法。通过使用不同的编码方式(UTF-8和GB2312)进行解码,并利用正则表达式判断解码后的字符串是否符合预期的编码格式,从而实现对URL中汉字的有效解码。

        最近遇到一些url中携带没有encode的汉字,并且这样的url有的是utf-8编码,有的又是gbk编码。最终这些url被记录下来的时候,必然就有一种情况url是乱码的。下面是解决的一个办法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace ConsoleApplication2 {
	class Program {
		public static string DecodeURL2(String uriString) {
			if (Regex.IsMatch(
				HttpUtility.UrlDecode(uriString, Encoding.GetEncoding("iso-8859-1")),
				@"^(?:[\x00-\x7f]|[\xe0-\xef][\x80-\xbf]{2})+$" // 如果不考虑哪些什么拉丁文啊,希腊文啊。。。乱七八糟的外文,用这个短的正则
			)) {
				return HttpUtility.UrlDecode(uriString, Encoding.GetEncoding("UTF-8"));
			} else {
				return HttpUtility.UrlDecode(uriString, Encoding.GetEncoding("GB2312"));
			}
		}

		public static string DecodeURL(String uriString) {
			if (Regex.IsMatch(
				HttpUtility.UrlDecode(uriString, Encoding.GetEncoding("iso-8859-1")),
				@"^(?:[\x00-\x7f]|[\xfc-\xff][\x80-\xbf]{5}|[\xf8-\xfb][\x80-\xbf]{4}|[\xf0-\xf7][\x80-\xbf]{3}|[\xe0-\xef][\x80-\xbf]{2}|[\xc0-\xdf][\x80-\xbf])+$"
			)) {
				return HttpUtility.UrlDecode(uriString, Encoding.GetEncoding("UTF-8"));
			} else {
				return HttpUtility.UrlDecode(uriString, Encoding.GetEncoding("GB2312"));
			}
		}

		public static void Main(string[] args) {
			Console.WriteLine("----------------------------------------------");
			Console.WriteLine(DecodeURL(".net%bc%bc%ca%f5"));
			Console.WriteLine(DecodeURL(".net%e6%8a%80%e6%9c%af"));


			Console.WriteLine("----------------------------------------------");
			Console.WriteLine(DecodeURL("%B8%A7%CB%B3%C7%E0%CB%C9%D2%A9%D2%B5"));
			Console.WriteLine(DecodeURL("%E6%8A%9A%E9%A1%BA%E9%9D%92%E6%9D%BE%E8%8D%AF%E4%B8%9A"));


			Console.WriteLine("------------------↓↓↓下面的出问题↓↓↓------------------");


			Console.WriteLine(DecodeURL("%E8%81%94%E9%80%9A")); // 正常
			Console.WriteLine(DecodeURL("%C1%AA%CD%A8")); // 发生编码误认
			// 编码误认,并没有好的解决方案,因为utf-8和gbk编码结果存在交叉,  我们都知道,记事本也都会出现这种情况

			Console.WriteLine("------------------↑↑↑上面的出问题↑↑↑------------------");


			Console.WriteLine(DecodeURL2("%E8%81%94%E9%80%9A")); // 正常
			Console.WriteLine(DecodeURL2("%C1%AA%CD%A8")); // 不会误认
			Console.WriteLine("----------------------------------------------");


			Console.ReadKey();
		}
	}
}

转载于:https://my.oschina.net/ajeelee/blog/137595

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值