URLエンコードのデコード

http://blog.zakura.jp/cal/2008/04/javaurldecoder.html

修正したバージョンをあげている人が見つからなかったので書いた。

import java.io.*;
import java.util.*;

public class URLDecoder {

    public static String decode(String s) throws UnsupportedEncodingException {
        return decode(s, "JISAutoDetect");
    }

    public static String decode(String s, String enc) throws UnsupportedEncodingException {

        boolean needToChange = false;
        int numChars = s.length();
        int i = 0;
        char c;
        byte[] bytes = new byte[numChars];
        int bytePos = 0;

        while (i < numChars) {
            c = s.charAt(i);
            switch (c) {
            case '+':
                bytes[bytePos++] = (byte)' ';
                i++;
                break;
            case '%':
                if (i + 3 > numChars)
                    throw new IllegalArgumentException("URLDecoder: Incomplete trailing escape (%) pattern");

                try {
                    bytes[bytePos++] = (byte)Integer.parseInt(s.substring(i + 1, i + 3), 16);
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException("URLDecoder: Illegal hex characters in escape (%) pattern - " + e.getMessage());
                }
                i += 3;
                break;
            default:
                bytes[bytePos++] = (byte)c;
                i++;
                break;
            }
        }

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes, 0, bytePos), enc));
            StringBuilder buffer = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            return buffer.toString();
        }  catch (IOException e) {
            throw new IllegalArgumentException("URLDecoder: something wrong - " + e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
            }
        }

    }

}

自分用の用途でしか動作確認をしていないので気をつけてください。JISAutoDetect は UTF を認識してくれないのがかなりいまいち。Java の日本語周りのちゃんとしたライブラリってないのかな。使えば使うほど嫌いになるわ、じゃばじゃば。