HttpUrl Parameter Encoding in Java – Percent Encoding

Some already know that there is URLEncoder class in java but not many know that this class is actually not for URL encoding but for form encoding if you have look at the javadocs. There are several other utility libraries as well doing this correctly like apache-commons but if you just need url encoding, it might be easier to use one utility class instead of loading a whole library.

public class URLParamEncoder {

    public static String encode(String input) {
        StringBuilder resultStr = new StringBuilder();
        for (char ch : input.toCharArray()) {
            if (isUnsafe(ch)) {
                resultStr.append('%');
                resultStr.append(toHex(ch / 16));
                resultStr.append(toHex(ch % 16));
            } else {
                resultStr.append(ch);
            }
        }
        return resultStr.toString();
    }

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

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

[1] https://en.wikipedia.org/wiki/Percent-encoding

Leave a Reply

Your email address will not be published. Required fields are marked *