生活随笔
收集整理的這篇文章主要介紹了
url的关键字不知道是uft-8还是GBK
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
? ? ? ? 最近遇到一些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
總結
以上是生活随笔為你收集整理的url的关键字不知道是uft-8还是GBK的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。