goo.glを利用する

いま作ってみようと思っているアプリで短縮URLが必要となりそうなので、goo.glの使い方を調べてみました。goo.glの公式サイトはこちらです。
goo.glは短縮したいURLをAPIにポストすると、結果をJSON形式で返却してきますが、それをイチイチ解析するのもアレなので、JSONICを利用してPOJOに変換するようにしました。JSONICは依存ライブラリもなく、使い方もシンプルなので使い易いですね。

/**
 * GoogleのURL短縮サービス「goo.gl」を利用するクラスです。
 * 
 * @author m_namiki
 * 
 */
public class Googl {

	private static final String API_URL = "https://www.googleapis.com/urlshortener/v1/url";

	/**
	 * 指定されたURLの短縮URLを返却します。
	 * 
	 * @param target
	 *            対象URL
	 * @return 短縮URL
	 */
	public static String shortener(String target) {
		try {
			URL url = new URL(API_URL);
			URLConnection urlConn = url.openConnection();
			urlConn.setDoOutput(true);
			urlConn.setRequestProperty("Content-Type", "application/json");

			PrintStream ps = new PrintStream(urlConn.getOutputStream());
			ps.print("{\"longUrl\": \"" + target + "\"}");
			ps.close();

			GooglJSON json = JSON.decode(urlConn.getInputStream(),
					GooglJSON.class);
			return json.getId();
		} catch (Exception cause) {
			throw new RuntimeException(cause);
		}
	}
}

APIにポストするときに、Content-Typeをapplication/jsonと指定することと、ポストの内容を以下のようなJSON形式とするだけです。

{“longUrl”: “http://www.google.com/”}

で、goo.glからの結果は以下のようなJSON形式です。

{
 "kind": "urlshortener#url",
 "id": "http://goo.gl/fbsS",
 "longUrl": "http://www.google.com/"
}

これをJSONICでPOJOに変換しているのがJSON#decode()の部分です。変換先のGooglJSONはkind,id,longUrlというプロパティとそれぞれのGetter/Setterを持ったPOJOとなります。