public static String escapeForUrl ( final String input ) { if ( input == null || input . length ( ) == 0 ) { return input ; } final StringBuilder buffer = new StringBuilder ( input . length ( ) * 2 ) ; // worst-case char [ ] characters = input . toCharArray ( ) ; for ( int i = 0 , len = input . length ( ) ; i < len ; ++ i ) { final char ch = characters [ i ] ; // Section 2.3 - Unreserved chars if ( ( ch >= ' ' && ch <= ' ' ) || ( ch >= ' ' && ch <= ' ' ) || ( ch >= ' ' && ch <= ' ' ) || ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' ) { buffer . append ( ch ) ; } else if ( ch <= 127 ) { // Other ASCII characters must be escaped final String hexString = Integer . toHexString ( ch ) ; if ( hexString . length ( ) == 1 ) { buffer . append ( "%0" ) . append ( hexString ) ; } else { buffer . append ( ' ' ) . append ( hexString ) ; } } else if ( ch <= 0x07FF ) { // Other non-ASCII chars must be UTF-8 encoded buffer . append ( ' ' ) . append ( Integer . toHexString ( 0xc0 | ( ch >> 6 ) ) ) ; buffer . append ( ' ' ) . append ( Integer . toHexString ( 0x80 | ( ch & 0x3F ) ) ) ; } else { buffer . append ( ' ' ) . append ( Integer . toHexString ( 0xe0 | ( ch >> 12 ) ) ) ; buffer . append ( ' ' ) . append ( Integer . toHexString ( 0x80 | ( ( ch >> 6 ) & 0x3F ) ) ) ; buffer . append ( ' ' ) . append ( Integer . toHexString ( 0x80 | ( ch & 0x3F ) ) ) ; } } return buffer . toString ( ) ; }
Escapes the given string to make it presentable in a URL . This follows RFC 3986 with some extensions for UTF - 8 .