集册 Java实例教程 用自己的算法编码URL

用自己的算法编码URL

欢马劈雪     最近更新时间:2020-01-02 10:19:05

472
用您自己的算法编码URL


//package com.nowjava;

import java.io.UnsupportedEncodingException;//时代Java 提 供


public class Main {

    public static String encodeURL(String s) {

        if (s == null)

            return "";

        StringBuilder sb = new StringBuilder();

        int i = 0, sl = s.length();

        for (; i < sl; ++i) {

            char sc = s.charAt(i);

            if (('0' <= sc && sc <= '9')

                    || ('a' <= sc && sc <= 'z')

                    || ('A' <= sc && sc <= 'Z')

                    || (";/?:@=&% $-_.+!*\'\"(),{}|\\^~[]".indexOf(sc) >= 0)) {

                sb.append(sc);

                continue;

            }/*时 代 J a v a - N o w J a v a . c o m*/

            try {

                byte[] bytes = new String(new char[] { sc })

                        .getBytes("UTF-8");

                int j = 0, bl = bytes.length;

                for (; j < bl; ++j) {

                    sb.append('%');

                    byte b = bytes[j];

                    char bc = Character.forDigit((b >> 4) & 0xf, 16);

                    if (('a' <= bc && bc <= 'z'))

                        bc -= 0x20;

                    sb.append(bc);

                    bc = Character.forDigit(b & 0xf, 16);

                    
展开阅读全文