The Grimoire of Nonsense

個人的なメモを残すブログ

C#でHTTPのリダイレクト先を調べるもの

リダイレクトされる先を調べるようなっぽいものを諸事情で作りました。
色々参考にしました。
一応、Google短縮URLサービスからここのブログ用のURL作ってテストはしました……です。
きっと色々突っ込み所はあると思うけど、気にしない方向で……(滝汗)


以下コード

using System;
using System.Net;

class HttpRequestViewer
{
	public static void View( string uri )
	{
		HttpWebRequest req = (HttpWebRequest)WebRequest.Create( uri );
		HttpWebResponse res = null;
		bool existLocation = false;

		req.AllowAutoRedirect = false;
		req.Method = "GET";
		res = (HttpWebResponse)req.GetResponse();

		Console.WriteLine( "HTTP/{0} {1} {2}", res.ProtocolVersion, (int)res.StatusCode, res.StatusDescription );

		foreach ( string key in res.Headers.AllKeys )
			Console.WriteLine( "{0}: {1}", key, res.Headers[key] );

		Console.WriteLine( "----" );
		existLocation = isExistLocation( res.Headers );

		if ( existLocation )
			View( res.Headers["Location"] );
	}

	private static bool isExistLocation( WebHeaderCollection collection )
	{
		string[] array = collection.AllKeys;
		int res = Array.IndexOf( array, "Location" );

		return res >= 0;
	}
}

最近目が悪くなったのか誤字を見落としやすくなった気がする……。