Android 中是否有使用完整百分比编码对字符串进行编码/解码的快速函数?

发布于 2024-11-03 05:14:08 字数 175 浏览 6 评论 0原文

我想在 Android 应用程序中对某些字符串操作使用百分比值编码/解码。我不想使用 URI 编码/解码函数对,因为我想对每个字符进行编码,而不仅仅是在对 URI 进行编码以发出 Web 请求时编码的字符。 Android 库或 Java 库中有内置函数可以做到这一点吗?

——罗施勒

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 built-in functions in the Android libraries or Java libraries that can do this?

-- roschler

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月隐月明月朦胧 2024-11-10 05:14:08

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++;
    }
}

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++;
    }
}
凉城凉梦凉人心 2024-11-10 05:14:08

这是非常简单的,并且不需要库函数:

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;
}

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文