public static String encodeSegment(String segment) {
        requireNonNull(segment, "segment");
        final StringBuilder sb = new StringBuilder(segment.length() + 1);
        sb.append('/');
        for (int i = 0, end = segment.length(); i < end; ++i) {
            char c = segment.charAt(i);
            if (c == '/') {
                sb.append("~1");
                continue;
            }
            if (c == '~') {
                sb.append("~0");
                continue;
            }
            sb.append(c);
        }
        return sb.toString();
    }
public static String encodeSegment ( String segment ) { requireNonNull ( segment , "segment" ) ; final StringBuilder sb = new StringBuilder ( segment . length ( ) + 1 ) ; sb . append ( '/' ) ; for ( int i = 0 , end = segment . length ( ) ; i < end ; ++ i ) { char c = segment . charAt ( i ) ; if ( c == '/' ) { sb . append ( "~1" ) ; continue ; } if ( c == '~' ) { sb . append ( "~0" ) ; continue ; } sb . append ( c ) ; } return sb . toString ( ) ; }
Adds a leading slash and replaces '/' and '~' with '~1' and '~0' respectively.
See <a href="https://tools.ietf.org/html/rfc6901">rfc6901</a> for more information.