Java URLDecoderクラスのdecode関数で%2Bをプラス記号にデコードするサンプル
環境
JavaSE 1.8
Eclipse 4.14.0
構文
public static String decode(String s,String enc) throws UnsupportedEncodingException
特定のエンコーディング方式を使ってapplication/x-www-form-urlencoded文字列をデコードします。指定されたエンコーディングに基づいて、「%xy」という形式の任意の連続するシーケンスがどの文字を表しているかが決定されます。
パラメータ:
s – デコードするString
enc – サポートされる文字エンコーディングの名前。
使用例
package com.arkgame.study;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
public class ArkgDemo {
// 文字コード
private static final String CHARSET = "UTF-8";
public static void main(String[] args) {
// URLの形式
String enstr = "user%2bbyamada";
System.out.println("%2Bをプラス記号へ変換する結果Before: " + enstr);
// 文字列をデコードする関数を呼び出す
String res = decodeFunc(enstr);
System.out.println("%2Bをプラス記号へ変換する結果End: " + res);
}
// デコード処理関数
static String decodeFunc(String val) {
String result;
try {
// decode関数を呼び出す
result = URLDecoder.decode(val, CHARSET);
return result;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getCause());
}
}
}
package com.arkgame.study;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
public class ArkgDemo {
// 文字コード
private static final String CHARSET = "UTF-8";
public static void main(String[] args) {
// URLの形式
String enstr = "user%2bbyamada";
System.out.println("%2Bをプラス記号へ変換する結果Before: " + enstr);
// 文字列をデコードする関数を呼び出す
String res = decodeFunc(enstr);
System.out.println("%2Bをプラス記号へ変換する結果End: " + res);
}
// デコード処理関数
static String decodeFunc(String val) {
String result;
try {
// decode関数を呼び出す
result = URLDecoder.decode(val, CHARSET);
return result;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getCause());
}
}
}
package com.arkgame.study; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; public class ArkgDemo { // 文字コード private static final String CHARSET = "UTF-8"; public static void main(String[] args) { // URLの形式 String enstr = "user%2bbyamada"; System.out.println("%2Bをプラス記号へ変換する結果Before: " + enstr); // 文字列をデコードする関数を呼び出す String res = decodeFunc(enstr); System.out.println("%2Bをプラス記号へ変換する結果End: " + res); } // デコード処理関数 static String decodeFunc(String val) { String result; try { // decode関数を呼び出す result = URLDecoder.decode(val, CHARSET); return result; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getCause()); } } }
実行結果
%2Bをプラス記号へ変換する結果Before: user%2bbyamada
%2Bをプラス記号へ変換する結果End: user+byamada
%2Bをプラス記号へ変換する結果Before: user%2bbyamada
%2Bをプラス記号へ変換する結果End: user+byamada
%2Bをプラス記号へ変換する結果Before: user%2bbyamada %2Bをプラス記号へ変換する結果End: user+byamada