encode URL in your own algorithm - Java Network

Java examples for Network:URL

Description

encode URL in your own algorithm

Demo Code


//package com.java2s;
import java.io.UnsupportedEncodingException;

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);//from w w  w  .  j a  v  a 2s  . c  o m
                continue;
            }
            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);
                    if (('a' <= bc && bc <= 'z'))
                        bc -= 0x20;
                    sb.append(bc);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

Related Tutorials