URLを短いアドレスに変換するサービスとしてTinyURLがここ最近地位を確立した感じですね。めっちゃ短いアドレスというわけでもないけど、はやった要因はなんだったんでしょう。広告? API?
そんなわけで、長いURLからTinyURLを取得するコードを書いてみたいと思います。せっかくなので(?)手元にあるMicrosoft製のコードをみます。
そのコードは、Windows Live Writer SDK 1.1のサンプルにあります。Twitterプラグインのコード中にMakeTinyUrlというメソッドがあります。
private string MakeTinyUrl(string url)
{
if (UrlShortener.Length == 0)
return url;
return TaskServices.ExecuteWithResponsiveUI(url, delegate
{
using (WebClient wc = new WebClient())
return wc.DownloadString(string.Format(UrlShortener, url, HttpUtility.UrlEncode(url)));
});
}
TaskServicesは、時間のかかる処理を行う場合に利用するクラスですね。WebClientを生成して、あるURLにアクセスしてダウンロードした文字列を返してます。URL部分を指定するUrlShortenerの定義は次のようになってます。
private string UrlShortener
{
get
{
// {0} is the long URL, {1} is the same but URL-encoded.
//
// Other possibilities:
// http://is.gd/api.php?longurl={0}
// http://snipr.com/site/snip?r=simple&link={1}
// http://snurl.com/site/snip?r=simple&link={1}
// {0}
string format = Options.GetString("UrlShortener", null);
return !string.IsNullOrEmpty(format) ? format : "http://tinyurl.com/api-create.php?url={0}";
}
}
コメントでTinyURL以外のサービスについても書いてますね。Optionsは、Writer用の設定を管理しているクラスです。TinyURLの場合、http://tinyurl.com/api-create.php?url=~にアクセスすれば良いみたいですね。
UrlShortenerにより、さっきのMakeTinyUrlメソッド内のstring.Format内用の文字列が返り、他のサービスも想定してエンコードなしとありのURLを設定していたわけですね。
VBで書くと次のような感じ。
Function MakeTinyUrl(ByVal url As String) As String
Return (New WebClient).DownloadString("http://tinyurl.com/api-create.php?url=" & url)
End Function
これは自分のプログラムでも使っていこう。