短縮URLなんかのリダイレクト先を取得するコードを書いてみました。
こんどは、Java7構文の文字列によるswitch文を使ってます。
やっぱり、文字列でswitchできるというのはうれしいです。あと、内部的に最適な分岐判定をやってくれるんじゃないかという期待も。
package sample.net; import java.io.*; import java.net.*; import java.util.Date; public class GetRedirect { public static void main(String[] args) throws MalformedURLException, IOException{ URL u = new URL("http://goo.gl/AXxvG"); System.out.println("リダイレクト先:" + GetRedirect.getRedirectUrl(u)); } public static String getRedirectUrl(URL u) throws IOException{ String host = u.getHost(); int port = u.getPort(); if(port < 0) port = 80;//デフォルトは80番 try( //接続準備 Socket soc = new Socket(host, port); OutputStream os = soc.getOutputStream(); PrintWriter pw = new PrintWriter(os); InputStream is = soc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader bur = new BufferedReader(isr); ){ //リクエスト送信 pw.printf("GET %s HTTP/1.1\r\n", u.getPath()); pw.printf("Host: %s:%d\r\n", host, port); pw.print("\r\n"); pw.flush(); //ステータス取得 String line = bur.readLine(); System.out.println(line); if(line == null) throw new IOException("no header");//終わる ヘッダーがない String[] status = line.split(" "); if(status.length < 2) throw new IOException("wrong header");//ヘッダーがおかしい switch(status[1]){ case "301":// Moved Permanently case "302":// Moved Temporarily break; default: throw new IOException("not redirect");//リダイレクトじゃない } String result = null; while((line = bur.readLine()) != null){ //ヘッダー解析 int pos = line.indexOf(':'); if(pos < 0) break;//ヘッダー終わり //ヘッダー名 String name = line.substring(0, pos); //ヘッダー値 String value = line.substring(pos + 1); if(value.length() < 1) continue;//値がない value = value.substring(1); //ヘッダごとの処理 switch(name){ case "Location": System.out.println("飛び先:" + value); result = value; break; case "Last-Modified": System.out.println(value); break; default: } } System.out.println(); return result; } } }