使用URI中允许的字符集对字符串进行编码。
/** * Copyright (c) 2000-2016 Liferay, Inc. 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. */ //package com.nowjava; /**来自 NowJava.com - 时 代 Java**/ import java.io.UnsupportedEncodingException; public class Main { private static final boolean[] sValidChar = new boolean[128]; private static final char[] sHexLookup = new char[16]; /** * Encodes a String using the set of characters allowed in a URI. This method encodes a multibyte string in UTF8 * * @param value <code>String</code> to be translated. * * @return the translated <code>String</code>. */ public static String encodeUTF(String value) { String encodedValue = null; try { encodedValue = encode(value, "UTF8"); } catch (UnsupportedEncodingException e) { // TODO - error handling // should never happen for this method because the // character encoding is constant//来自 n o w j a v a . c o m - 时代Java } return encodedValue; } /** * Encodes a String using the set of characters allowed in a URI. * * @param value <code>String</code> to be translated. * @param encoding the Java alias for the character encoding to be used to convert non-ASCII characters into * bytes (e.g. <code>"UTF8"</code>). * * @return the translated <code>String</code>. * * @exception UnsupportedEncodingException if the given encoding is not a recognised character encoding. */ public static String encode(String value, String encoding) throws UnsupportedEncodingException { // Create a buffer that is roughly 1.5 times bigger than the value to // account for possible expansion of the resulting encoded string int len = value.length(); StringBuilder out = new StringBuilder(len * 3 / 2); for (int charIndex = 0; charIndex < len; charIndex++) { char aChar = value.charAt(charIndex); if ((aChar <= 127) && sValidChar[aChar]) { out.append(aChar); } else if (aChar == ' ') { out.append('+'); } else { byte[] charBytes = String.valueOf(aChar).getBytes(encoding); // For each byte to encode this character, write a '%',