スキップしてメイン コンテンツに移動

Commons Codec でURLをエンコード・デコード


Commons Codec の Base64#encodeBase64URLSafeString。
ただのBase64変換ではなく、
URLで使えない「+」と「/」を、それぞれ「-」と「_」で変換してくれる。

こんなときに便利。
  • バイナリデータを文字列(URL)で扱いたいとき。
  • URLEncoder/URLDecoderだと+や/が困るとき。
使い方はこんな感じ。


import org.apache.commons.codec.binary.Base64;
・・・
byte[] binaryData = "あいうえお".getBytes("UTF-8"); // 変換したいデータ
String safestr = Base64.encodeBase64URLSafeString(binaryData); // エンコード
System.out.println(safestr);
byte[] b = Base64.decodeBase64(safestr); // デコード
System.out.println(new String(b, "UTF-8"));