Is there a quick function to encode/decode strings in Android using full percent encoding?
I want to use percent value encoding/decoding for some string operations in my Android application. I don't want to use a URI encode/decode function pair because I want to encode every character, not just the ones that are encoded when encoding URI's for making web requests. Are there any bu开发者_高级运维ilt-in functions in the Android libraries or Java libraries that can do this?
-- roschler
There's nothing built in to the API to do this directly, but it's pretty simple. It's better to use a specific character encoding (like UTF-8) to convert characters to bytes. This should do the trick for encoding:
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));
}
}
Oh yes, you asked for decoding as well:
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++;
}
}
This is pretty trivial, and doesn't need library functions:
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;
}
精彩评论