1. /*
  2. * @(#)URLEncoder.java 1.28 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.net;
  8. import java.io.ByteArrayOutputStream;
  9. import java.io.BufferedWriter;
  10. import java.io.OutputStreamWriter;
  11. import java.io.IOException;
  12. import java.io.UnsupportedEncodingException;
  13. import java.util.BitSet;
  14. import java.security.AccessController;
  15. import java.security.PrivilegedAction;
  16. import sun.security.action.GetBooleanAction;
  17. import sun.security.action.GetPropertyAction;
  18. /**
  19. * Utility class for HTML form encoding. This class contains static methods
  20. * for converting a String to the <CODE>application/x-www-form-urlencoded</CODE> MIME
  21. * format. For more information about HTML form encoding, consult the HTML
  22. * <A HREF="http://www.w3.org/TR/html4/">specification</A>.
  23. *
  24. * <p>
  25. * When encoding a String, the following rules apply:
  26. *
  27. * <p>
  28. * <ul>
  29. * <li>The alphanumeric characters "<code>a</code>" through
  30. * "<code>z</code>", "<code>A</code>" through
  31. * "<code>Z</code>" and "<code>0</code>"
  32. * through "<code>9</code>" remain the same.
  33. * <li>The special characters "<code>.</code>",
  34. * "<code>-</code>", "<code>*</code>", and
  35. * "<code>_</code>" remain the same.
  36. * <li>The space character "<code> </code>" is
  37. * converted into a plus sign "<code>+</code>".
  38. * <li>All other characters are unsafe and are first converted into
  39. * one or more bytes using some encoding scheme. Then each byte is
  40. * represented by the 3-character string
  41. * "<code>%<i>xy</i></code>", where <i>xy</i> is the
  42. * two-digit hexadecimal representation of the byte.
  43. * The recommended encoding scheme to use is UTF-8. However,
  44. * for compatibility reasons, if an encoding is not specified,
  45. * then the default encoding of the platform is used.
  46. * </ul>
  47. *
  48. * <p>
  49. * For example using UTF-8 as the encoding scheme the string "The
  50. * string ü@foo-bar" would get converted to
  51. * "The+string+%C3%BC%40foo-bar" because in UTF-8 the character
  52. * ü is encoded as two bytes C3 (hex) and BC (hex), and the
  53. * character @ is encoded as one byte 40 (hex).
  54. *
  55. * @author Herb Jellinek
  56. * @version 1.28, 01/23/03
  57. * @since JDK1.0
  58. */
  59. public class URLEncoder {
  60. static BitSet dontNeedEncoding;
  61. static final int caseDiff = ('a' - 'A');
  62. static String dfltEncName = null;
  63. static {
  64. /* The list of characters that are not encoded has been
  65. * determined as follows:
  66. *
  67. * RFC 2396 states:
  68. * -----
  69. * Data characters that are allowed in a URI but do not have a
  70. * reserved purpose are called unreserved. These include upper
  71. * and lower case letters, decimal digits, and a limited set of
  72. * punctuation marks and symbols.
  73. *
  74. * unreserved = alphanum | mark
  75. *
  76. * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
  77. *
  78. * Unreserved characters can be escaped without changing the
  79. * semantics of the URI, but this should not be done unless the
  80. * URI is being used in a context that does not allow the
  81. * unescaped character to appear.
  82. * -----
  83. *
  84. * It appears that both Netscape and Internet Explorer escape
  85. * all special characters from this list with the exception
  86. * of "-", "_", ".", "*". While it is not clear why they are
  87. * escaping the other characters, perhaps it is safest to
  88. * assume that there might be contexts in which the others
  89. * are unsafe if not escaped. Therefore, we will use the same
  90. * list. It is also noteworthy that this is consistent with
  91. * O'Reilly's "HTML: The Definitive Guide" (page 164).
  92. *
  93. * As a last note, Intenet Explorer does not encode the "@"
  94. * character which is clearly not unreserved according to the
  95. * RFC. We are being consistent with the RFC in this matter,
  96. * as is Netscape.
  97. *
  98. */
  99. dontNeedEncoding = new BitSet(256);
  100. int i;
  101. for (i = 'a'; i <= 'z'; i++) {
  102. dontNeedEncoding.set(i);
  103. }
  104. for (i = 'A'; i <= 'Z'; i++) {
  105. dontNeedEncoding.set(i);
  106. }
  107. for (i = '0'; i <= '9'; i++) {
  108. dontNeedEncoding.set(i);
  109. }
  110. dontNeedEncoding.set(' '); /* encoding a space to a + is done
  111. * in the encode() method */
  112. dontNeedEncoding.set('-');
  113. dontNeedEncoding.set('_');
  114. dontNeedEncoding.set('.');
  115. dontNeedEncoding.set('*');
  116. dfltEncName = (String)AccessController.doPrivileged (
  117. new GetPropertyAction("file.encoding")
  118. );
  119. }
  120. /**
  121. * You can't call the constructor.
  122. */
  123. private URLEncoder() { }
  124. /**
  125. * Translates a string into <code>x-www-form-urlencoded</code>
  126. * format. This method uses the platform's default encoding
  127. * as the encoding scheme to obtain the bytes for unsafe characters.
  128. *
  129. * @param s <code>String</code> to be translated.
  130. * @deprecated The resulting string may vary depending on the platform's
  131. * default encoding. Instead, use the encode(String,String)
  132. * method to specify the encoding.
  133. * @return the translated <code>String</code>.
  134. */
  135. public static String encode(String s) {
  136. String str = null;
  137. try {
  138. str = encode(s, dfltEncName);
  139. } catch (UnsupportedEncodingException e) {
  140. // The system should always have the platform default
  141. }
  142. return str;
  143. }
  144. /**
  145. * Translates a string into <code>application/x-www-form-urlencoded</code>
  146. * format using a specific encoding scheme. This method uses the
  147. * supplied encoding scheme to obtain the bytes for unsafe
  148. * characters.
  149. * <p>
  150. * <em><strong>Note:</strong> The <a href=
  151. * "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
  152. * World Wide Web Consortium Recommendation</a> states that
  153. * UTF-8 should be used. Not doing so may introduce
  154. * incompatibilites.</em>
  155. *
  156. * @param s <code>String</code> to be translated.
  157. * @param enc The name of a supported
  158. * <a href="../lang/package-summary.html#charenc">character
  159. * encoding</a>.
  160. * @return the translated <code>String</code>.
  161. * @exception UnsupportedEncodingException
  162. * If the named encoding is not supported
  163. * @see URLDecoder#decode(java.lang.String, java.lang.String)
  164. * @since 1.4
  165. */
  166. public static String encode(String s, String enc)
  167. throws UnsupportedEncodingException {
  168. boolean needToChange = false;
  169. boolean wroteUnencodedChar = false;
  170. int maxBytesPerChar = 10; // rather arbitrary limit, but safe for now
  171. StringBuffer out = new StringBuffer(s.length());
  172. ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
  173. OutputStreamWriter writer = new OutputStreamWriter(buf, enc);
  174. for (int i = 0; i < s.length(); i++) {
  175. int c = (int) s.charAt(i);
  176. //System.out.println("Examining character: " + c);
  177. if (dontNeedEncoding.get(c)) {
  178. if (c == ' ') {
  179. c = '+';
  180. needToChange = true;
  181. }
  182. //System.out.println("Storing: " + c);
  183. out.append((char)c);
  184. wroteUnencodedChar = true;
  185. } else {
  186. // convert to external encoding before hex conversion
  187. try {
  188. if (wroteUnencodedChar) { // Fix for 4407610
  189. writer = new OutputStreamWriter(buf, enc);
  190. wroteUnencodedChar = false;
  191. }
  192. writer.write(c);
  193. /*
  194. * If this character represents the start of a Unicode
  195. * surrogate pair, then pass in two characters. It's not
  196. * clear what should be done if a bytes reserved in the
  197. * surrogate pairs range occurs outside of a legal
  198. * surrogate pair. For now, just treat it as if it were
  199. * any other character.
  200. */
  201. if (c >= 0xD800 && c <= 0xDBFF) {
  202. /*
  203. System.out.println(Integer.toHexString(c)
  204. + " is high surrogate");
  205. */
  206. if ( (i+1) < s.length()) {
  207. int d = (int) s.charAt(i+1);
  208. /*
  209. System.out.println("\tExamining "
  210. + Integer.toHexString(d));
  211. */
  212. if (d >= 0xDC00 && d <= 0xDFFF) {
  213. /*
  214. System.out.println("\t"
  215. + Integer.toHexString(d)
  216. + " is low surrogate");
  217. */
  218. writer.write(d);
  219. i++;
  220. }
  221. }
  222. }
  223. writer.flush();
  224. } catch(IOException e) {
  225. buf.reset();
  226. continue;
  227. }
  228. byte[] ba = buf.toByteArray();
  229. for (int j = 0; j < ba.length; j++) {
  230. out.append('%');
  231. char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
  232. // converting to use uppercase letter as part of
  233. // the hex value if ch is a letter.
  234. if (Character.isLetter(ch)) {
  235. ch -= caseDiff;
  236. }
  237. out.append(ch);
  238. ch = Character.forDigit(ba[j] & 0xF, 16);
  239. if (Character.isLetter(ch)) {
  240. ch -= caseDiff;
  241. }
  242. out.append(ch);
  243. }
  244. buf.reset();
  245. needToChange = true;
  246. }
  247. }
  248. return (needToChange? out.toString() : s);
  249. }
  250. }