001 /* URLEncoder.java -- Class to convert strings to a properly encoded URL
002 Copyright (C) 1998, 1999, 2001, 2002, 2003 Free Software Foundation, Inc.
003
004 This file is part of GNU Classpath.
005
006 GNU Classpath is free software; you can redistribute it and/or modify
007 it under the terms of the GNU General Public License as published by
008 the Free Software Foundation; either version 2, or (at your option)
009 any later version.
010
011 GNU Classpath is distributed in the hope that it will be useful, but
012 WITHOUT ANY WARRANTY; without even the implied warranty of
013 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014 General Public License for more details.
015
016 You should have received a copy of the GNU General Public License
017 along with GNU Classpath; see the file COPYING. If not, write to the
018 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
019 02110-1301 USA.
020
021 Linking this library statically or dynamically with other modules is
022 making a combined work based on this library. Thus, the terms and
023 conditions of the GNU General Public License cover the whole
024 combination.
025
026 As a special exception, the copyright holders of this library give you
027 permission to link this library with independent modules to produce an
028 executable, regardless of the license terms of these independent
029 modules, and to copy and distribute the resulting executable under
030 terms of your choice, provided that you also meet, for each linked
031 independent module, the terms and conditions of the license of that
032 module. An independent module is a module which is not derived from
033 or based on this library. If you modify this library, you may extend
034 this exception to your version of the library, but you are not
035 obligated to do so. If you do not wish to do so, delete this
036 exception statement from your version. */
037
038 package java.net;
039
040 import gnu.java.lang.CPStringBuilder;
041
042 import java.io.UnsupportedEncodingException;
043
044
045 /*
046 * Written using on-line Java Platform 1.2/1.4 API Specification, as well
047 * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
048 * Status: Believed complete and correct.
049 */
050
051 /**
052 * This utility class contains static methods that converts a
053 * string into a fully encoded URL string in x-www-form-urlencoded
054 * format. This format replaces certain disallowed characters with
055 * encoded equivalents. All upper case and lower case letters in the
056 * US alphabet remain as is, the space character (' ') is replaced with
057 * '+' sign, and all other characters are converted to a "%XX" format
058 * where XX is the hexadecimal representation of that character in a
059 * certain encoding (by default, the platform encoding, though the
060 * standard is "UTF-8").
061 * <p>
062 * This method is very useful for encoding strings to be sent to CGI scripts
063 *
064 * @author Aaron M. Renn (arenn@urbanophile.com)
065 * @author Warren Levy (warrenl@cygnus.com)
066 * @author Mark Wielaard (mark@klomp.org)
067 */
068 public class URLEncoder
069 {
070 /**
071 * This method translates the passed in string into x-www-form-urlencoded
072 * format using the default encoding. The standard encoding is
073 * "UTF-8", and the two-argument form of this method should be used
074 * instead.
075 *
076 * @param s The String to convert
077 *
078 * @return The converted String
079 *
080 * @deprecated
081 */
082 public static String encode(String s)
083 {
084 try
085 {
086 // We default to 8859_1 for compatibility with the same
087 // default elsewhere in the library.
088 return encode(s, System.getProperty("file.encoding", "8859_1"));
089 }
090 catch (UnsupportedEncodingException uee)
091 {
092 // Should never happen since default should always be supported
093 return s;
094 }
095 }
096
097 /**
098 * This method translates the passed in string into x-www-form-urlencoded
099 * format using the character encoding to hex-encode the unsafe characters.
100 *
101 * @param s The String to convert
102 * @param encoding The encoding to use for unsafe characters
103 *
104 * @return The converted String
105 *
106 * @exception UnsupportedEncodingException If the named encoding is not
107 * supported
108 *
109 * @since 1.4
110 */
111 public static String encode(String s, String encoding)
112 throws UnsupportedEncodingException
113 {
114 int length = s.length();
115 int start = 0;
116 int i = 0;
117
118 CPStringBuilder result = new CPStringBuilder(length);
119 while (true)
120 {
121 while (i < length && isSafe(s.charAt(i)))
122 i++;
123
124 // Safe character can just be added
125 result.append(s.substring(start, i));
126
127 // Are we done?
128 if (i >= length)
129 return result.toString();
130 else if (s.charAt(i) == ' ')
131 {
132 result.append('+'); // Replace space char with plus symbol.
133 i++;
134 }
135 else
136 {
137 // Get all unsafe characters
138 start = i;
139 char c;
140 while (i < length && (c = s.charAt(i)) != ' ' && ! isSafe(c))
141 i++;
142
143 // Convert them to %XY encoded strings
144 String unsafe = s.substring(start, i);
145 byte[] bytes = unsafe.getBytes(encoding);
146 for (int j = 0; j < bytes.length; j++)
147 {
148 result.append('%');
149 int val = bytes[j];
150 result.append(hex.charAt((val & 0xf0) >> 4));
151 result.append(hex.charAt(val & 0x0f));
152 }
153 }
154 start = i;
155 }
156 }
157
158 /**
159 * Private static method that returns true if the given char is either
160 * a uppercase or lowercase letter from 'a' till 'z', or a digit froim
161 * '0' till '9', or one of the characters '-', '_', '.' or '*'. Such
162 * 'safe' character don't have to be url encoded.
163 */
164 private static boolean isSafe(char c)
165 {
166 return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
167 || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.'
168 || c == '*');
169 }
170
171 /**
172 * Private constructor that does nothing. Included to avoid a default
173 * public constructor being created by the compiler.
174 */
175 private URLEncoder()
176 {
177 }
178
179 /**
180 * Used to convert to hex. We don't use Integer.toHexString, since
181 * it converts to lower case (and the Sun docs pretty clearly
182 * specify upper case here), and because it doesn't provide a
183 * leading 0.
184 */
185 private static final String hex = "0123456789ABCDEF";
186 }