Java String Encode encodePath(String path)

Here you can find the source of encodePath(String path)

Description

URL encode a path string using UTF-8.

License

Apache License

Declaration

public static String encodePath(String path) 

Method Source Code

//package com.java2s;
/*// w  w w  .jav a2 s . c  om
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  The ASF licenses this file to You
 * under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.  For additional information regarding
 * copyright in this work, please see the NOTICE file in the top level
 * directory of this distribution.
 */

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

public class Main {
    /**
     * URL encode a path string using UTF-8. The path separator '/' will not be encoded
     */
    public static String encodePath(String path) {
        int i = path.indexOf('/');
        StringBuilder sb = new StringBuilder();
        while (i != -1) {
            sb.append(encode(path.substring(0, i))).append('/');
            path = path.substring(i + 1);
            i = path.indexOf('/');
        }
        sb.append(encode(path));
        return sb.toString();
    }

    /**
     * URL encode a string using UTF-8.
     */
    public static String encode(String str) {
        String encodedStr = str;
        try {
            encodedStr = URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            // ignored
        }
        return encodedStr;
    }
}

Related

  1. encodeParameters(Map params, String paramsEncoding)
  2. encodeParams(final Map params)
  3. encodeParams(Map nameValuePairs)
  4. encodeParams(String encoding, String... params)
  5. EncodePath(String path)
  6. encodePath(String str)
  7. encodeRfc5849(final String value)
  8. encodeSpecialMdxCharactersInNames(String name)
  9. encodeState(Map params)