Here you can find the source of encodeUrl(final String input)
Parameter | Description |
---|---|
input | the input string to be URL encoded |
Parameter | Description |
---|---|
UnsupportedEncodingException | if "US-ASCII" charset is not available |
static String encodeUrl(final String input) throws UnsupportedEncodingException
//package com.java2s; /*//from w ww . j a v a 2 s . co m * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * 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. */ import java.io.UnsupportedEncodingException; import java.util.BitSet; public class Main { /** * The default charset used for URL encoding. */ private static final String US_ASCII = "US-ASCII"; /** * Radix used in encoding. */ private static final int RADIX = 16; /** * The escape character used for the URL encoding scheme. */ private static final char ESCAPE_CHAR = '%'; /** * BitSet of RFC 2392 safe URL characters. */ private static final BitSet SAFE_URL = new BitSet(256); /** * Encodes an input string according to RFC 2392. Unsafe characters are escaped. * * @param input the input string to be URL encoded * @return a URL encoded string * @throws UnsupportedEncodingException if "US-ASCII" charset is not available * @see <a href="http://tools.ietf.org/html/rfc2392">RFC 2392</a> */ static String encodeUrl(final String input) throws UnsupportedEncodingException { if (input == null) { return null; } final StringBuilder builder = new StringBuilder(); for (final byte c : input.getBytes(US_ASCII)) { int b = c; if (b < 0) { b = 256 + b; } if (SAFE_URL.get(b)) { builder.append((char) b); } else { builder.append(ESCAPE_CHAR); final char hex1 = Character.toUpperCase(Character.forDigit( (b >> 4) & 0xF, RADIX)); final char hex2 = Character.toUpperCase(Character.forDigit( b & 0xF, RADIX)); builder.append(hex1); builder.append(hex2); } } return builder.toString(); } }