Java URL Encode encodeUrlPath(String pathSegment)

Here you can find the source of encodeUrlPath(String pathSegment)

Description

encode Url Path

License

Open Source License

Parameter

Parameter Description
pathSegment a parameter

Return

escaped path segment, suitable for url

Declaration

public static String encodeUrlPath(String pathSegment) 

Method Source Code


//package com.java2s;
/*//from  w  w w. java2s.  co m
 * Copyright (c) 2012, Mo Maison. All Rights Reserved.
 *
 * Licensed 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.
 *
 */

import java.io.UnsupportedEncodingException;

public class Main {
    /**
     * @param pathSegment
     * @return escaped path segment, suitable for url
     */
    public static String encodeUrlPath(String pathSegment) {
        final StringBuilder sb = new StringBuilder();

        try {
            for (int i = 0; i < pathSegment.length(); i++) {
                final char c = pathSegment.charAt(i);

                if (((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9'))
                        || (c == '-') || (c == '.') || (c == '_') || (c == '~')) {
                    sb.append(c);
                } else {
                    final byte[] bytes = String.valueOf(c).getBytes("UTF-8");
                    for (byte b : bytes) {
                        sb.append('%') //
                                .append(Integer.toHexString((b >> 4) & 0xf)) //
                                .append(Integer.toHexString(b & 0xf));
                    }
                }
            }

            return sb.toString();
        } catch (UnsupportedEncodingException ex) {
            // does not occur, but in case :
            throw new RuntimeException(ex);
        }
    }
}

Related

  1. encodeUrl(final String input)
  2. encodeURL(String s)
  3. encodeURL(String s)
  4. encodeUrl(String url, String encoding)
  5. encodeURLComponent(final String s)
  6. unpaddedBase64UrlEncoded(final String unencodedString)
  7. uriDecode(String src)
  8. uriDecode(String uri)
  9. uriEncode(String uriRef)