Converts a string into something you can safely insert into a URL. - Java Network

Java examples for Network:URL

Description

Converts a string into something you can safely insert into a URL.

Demo Code


//package com.java2s;

public class Main {
    /** Converts a string into something you can safely insert into a URL. */
    public static String encodeURIcomponent(String s) {
        StringBuilder o = new StringBuilder();
        for (char ch : s.toCharArray()) {
            if (isUnsafe(ch)) {
                o.append('%');
                o.append(toHex(ch / 16));
                o.append(toHex(ch % 16));
            } else
                o.append(ch);/*  w w w .  ja  v  a  2 s.  c  o m*/
        }
        return o.toString();
    }

    private static boolean isUnsafe(char ch) {
        if (ch > 128 || ch < 0)
            return true;
        return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
    }

    private static char toHex(int ch) {
        return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
    }
}

Related Tutorials