Java Path Encode encodePathSegment(final String pathSegment)

Here you can find the source of encodePathSegment(final String pathSegment)

Description

Encodes a string to be a valid path segment, which means it can contain PCHAR* only (do not put path parameters or they will be escaped.

License

Open Source License

Declaration

public static String encodePathSegment(final String pathSegment) 

Method Source Code


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

public class Main {
    /**/*w ww .  j  av a  2s . com*/
     * path_segment = pchar <without> ";"
     */
    public final static BitSet PATH_SEGMENT = new BitSet();

    /**
     * Encodes a string to be a valid path segment, which means it can contain PCHAR* only (do not put path parameters or
     * they will be escaped. Uses UTF-8.
     */
    public static String encodePathSegment(final String pathSegment) {
        try {
            return encodePart(pathSegment, "UTF-8", PATH_SEGMENT);
        } catch (final UnsupportedEncodingException e) {
            // should not happen
            throw new RuntimeException(e);
        }
    }

    /**
     * Encodes a string to be a valid URI part, with the given characters allowed. The rest will be encoded.
     *
     * @throws java.io.UnsupportedEncodingException
     *
     */
    public static String encodePart(final String part, final String charset, final BitSet allowed)
            throws UnsupportedEncodingException {
        if (part == null) {
            return null;
        }
        // start at *3 for the worst case when everything is %encoded on one byte
        final StringBuffer encoded = new StringBuffer(part.length() * 3);
        final char[] toEncode = part.toCharArray();
        for (final char c : toEncode) {
            if (allowed.get(c)) {
                encoded.append(c);
            } else {
                final byte[] bytes = String.valueOf(c).getBytes(charset);
                for (final byte b : bytes) {
                    // make it unsigned
                    final int u8 = b & 0xFF;
                    encoded.append(String.format("%%%1$02X", u8));
                }
            }
        }
        return encoded.toString();
    }
}

Related

  1. encodePath(String path)
  2. encodePath(String path)
  3. encodePath(String path)
  4. encodePath(String path, boolean encodeSlash, String charset)
  5. encodePath(String url)