URLのデコード・アンエスケープを行うためのメソッドとしてHttpUtility.UrlDecodeとUri.UnescapeDataStringの二つがある。 それぞれの違いは下表の通り。
相違点 | HttpUtility.UrlDecode | Uri.UnescapeDataString |
アセンブリ | System.Web.dll | System.dll |
エンコーディングの指定 | 可 | 不可(UTF-8のみ) |
URL中の'+'の扱い | 空白に置換 | そのまま |
事前にUri.UnescapeDataStringに渡す文字列の'+'を'%20'に置換すればHttpUtility.UrlDecodeの結果と同じになる一方で、
- UTF-8以外でエンコードされた文字列を扱う必要があるか
- System.Web.dllを参照することが望ましいか
どうかによってどちらを使うか判断する必要がある。
HttpUtility.UrlDecodeとUri.UnescapeDataStringの比較用サンプル
// gmcs -r:System.Web test.cs && mono test.exe
using System;
using System.Text;
using System.Web;
class UrlDecodeTest {
static void Main()
{
var urlUtf8 = "http://www.google.co.jp/search?q=.NET+Framework+2.0+%E3%83%A9%E3%83%B3%E3%82%BF%E3%82%A4%E3%83%A0&ie=UTF8";
var urlEucJp = "http://www.google.co.jp/search?q=.NET+Framework+2.0+%a5%e9%a5%f3%a5%bf%a5%a4%a5%e0&ie=EUC-JP";
Console.WriteLine("URL with UTF-8 encoded query");
Console.WriteLine(" {0,-32} : {1}", "URL", urlUtf8);
Console.WriteLine(" {0,-32} : {1}", "HttpUtility.UrlDecode", HttpUtility.UrlDecode(urlUtf8));
Console.WriteLine(" {0,-32} : {1}", "Uri.UnescapeDataString", Uri.UnescapeDataString(urlUtf8));
Console.WriteLine(" {0,-32} : {1}", "Uri.UnescapeDataString+Replace", Uri.UnescapeDataString(urlUtf8.Replace("+", "%20")));
Console.WriteLine();
Console.WriteLine("URL with EUC-JP encoded query");
Console.WriteLine(" {0,-32} : {1}", "URL", urlEucJp);
Console.WriteLine(" {0,-32} : {1}", "HttpUtility.UrlDecode", HttpUtility.UrlDecode(urlEucJp, Encoding.GetEncoding("euc-jp")));
Console.WriteLine(" {0,-32} : {1}", "Uri.UnescapeDataString", Uri.UnescapeDataString(urlEucJp));
Console.WriteLine(" {0,-32} : {1}", "Uri.UnescapeDataString+Replace", Uri.UnescapeDataString(urlEucJp.Replace("+", "%20")));
}
}
実行結果
URL with UTF-8 encoded query URL : http://www.google.co.jp/search?q=.NET+Framework+2.0+%E3%83%A9%E3%83%B3%E3%82%BF%E3%82%A4%E3%83%A0&ie=UTF8 HttpUtility.UrlDecode : http://www.google.co.jp/search?q=.NET Framework 2.0 ランタイム&ie=UTF8 Uri.UnescapeDataString : http://www.google.co.jp/search?q=.NET+Framework+2.0+ランタイム&ie=UTF8 Uri.UnescapeDataString+Replace : http://www.google.co.jp/search?q=.NET Framework 2.0 ランタイム&ie=UTF8 URL with EUC-JP encoded query URL : http://www.google.co.jp/search?q=.NET+Framework+2.0+%a5%e9%a5%f3%a5%bf%a5%a4%a5%e0&ie=EUC-JP HttpUtility.UrlDecode : http://www.google.co.jp/search?q=.NET Framework 2.0 ランタイム&ie=EUC-JP Uri.UnescapeDataString : http://www.google.co.jp/search?q=.NET+Framework+2.0+������&ie=EUC-JP Uri.UnescapeDataString+Replace : http://www.google.co.jp/search?q=.NET Framework 2.0 ������&ie=EUC-JP