url编码,只对汉字有效

2022-02-10 14:13:54 浏览数 (1)

代码语言:javascript复制
public static String toUtf8String(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i  ) {
            char c = s.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = String.valueOf(c).getBytes("utf-8");
                } catch (Exception ex) {
                    System.out.println(ex);
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j  ) {
                    int k = b[j];
                    if (k < 0)
                        k  = 256;
                    sb.append("%"   Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

0 人点赞