UriCodec
ついでにURI文字列のコーデック。
/* UriCodec URI文字列⇔文字列の相互変換 */ import java.io.UnsupportedEncodingException; public class UriCodec{ // インスタンス化禁止 private UriCodec() {} /** URI文字列にエンコード。 * @param str エンコードする文字列 * @param charset 使用する文字コード */ public static String encode(String str, String charset) throws UnsupportedEncodingException { byte bytes = str.getBytes(charset); StringBuffer sb = new StringBuffer(); for(int i = 0 ; i < bytes.length ; i++){ sb.append("%"); sb.append(Integer.toHexString(bytes[i] & 0xff)); } return sb.toString(); } /** URI文字列をデコード * @param str デコードするURI文字列 * @param charset 使用する文字コード */ public static String decode(String str, String charset) throws UnsupportedEncodingException { byte bytes = new byte[str.length()]; int j = 0; for(int i = 0 ; i < str.length() ; i++){ if(str.charAt(i) == '%'){ bytes[j++] = (byte)Integer.parseInt(str.substring(i + 1, i + 3), 16); i += 2; }else{ bytes[j++] = (byte)str.charAt(i); } } return new String(bytes, 0, j, charset); } }
encode()がいいかげんすぎ*1<自分