Android アプリケーションの一部の文字列操作にパーセント値のエンコード/デコードを使用したいと考えています。Web リクエストを作成するために URI をエンコードするときにエンコードされる文字だけでなく、すべての文字をエンコードしたいので、URI エンコード/デコード関数のペアを使用したくありません。これを実行できる Android ライブラリまたは Java ライブラリの組み込み関数はありますか?
-- ロシュラー
Android アプリケーションの一部の文字列操作にパーセント値のエンコード/デコードを使用したいと考えています。Web リクエストを作成するために URI をエンコードするときにエンコードされる文字だけでなく、すべての文字をエンコードしたいので、URI エンコード/デコード関数のペアを使用したくありません。これを実行できる Android ライブラリまたは Java ライブラリの組み込み関数はありますか?
-- ロシュラー
これを直接行う API には何も組み込まれていませんが、非常に単純です。文字をバイトに変換するには、特定の文字エンコーディング (UTF-8 など) を使用することをお勧めします。これは、エンコードのトリックを行う必要があります。
static final String digits = "0123456789ABCDEF";
static void convert(String s, StringBuffer buf, String enc)
throws UnsupportedEncodingException {
byte[] bytes = s.getBytes(enc);
for (int j = 0; j < bytes.length; j++) {
buf.append('%');
buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
buf.append(digits.charAt(bytes[j] & 0xf));
}
}
そうそう、あなたもデコードを求めました:
static String decode(String s, String enc)
throws UnsupportedEncodingException {
StringBuffer result = new StringBuffer(s.length());
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int i = 0; i < s.length();) {
char c = s.charAt(i);
if (c == '%') {
out.reset();
do {
if (i + 2 >= s.length()) {
throw new IllegalArgumentException(
"Incomplete trailing escape (%) pattern at " + i);
}
int d1 = Character.digit(s.charAt(i + 1), 16);
int d2 = Character.digit(s.charAt(i + 2), 16);
if (d1 == -1 || d2 == -1) {
throw new IllegalArgumentException(
"Illegal characters in escape (%) pattern at " + i
+ ": " + s.substring(i, i+3));
}
out.write((byte) ((d1 << 4) + d2));
i += 3;
} while (i < s.length() && s.charAt(i) == '%');
result.append(out.toString(enc));
continue;
} else {
result.append(c);
}
i++;
}
}
これは非常に簡単で、ライブラリ関数は必要ありません。
public static String escapeString(String input) {
String output = "";
for (byte b : input.getBytes()) output += String.format("%%%02x", b);
return output;
}
public static String unescapeString(String input) {
String output = "";
for (String hex: input.split("%")) if (!"".equals(hex)) output += (char)Integer.parseInt(hex, 16);
return output;
}
public static String unescapeMultiByteString(String input, String charset) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
String result = null;
for (String hex: input.split("%")) if (!"".equals(hex)) output.write(Integer.parseInt(hex, 16));
try { result = new String(output.toByteArray(), charset); }
catch (Exception e) {}
return result;
}