1. /*
  2. * @(#)URLEncoder.java 1.30 04/05/18
  3. *
  4. * Copyright 2004 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.30, 05/18/04
  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. @Deprecated
  136. public static String encode(String s) {
  137. String str = null;
  138. try {
  139. str = encode(s, dfltEncName);
  140. } catch (UnsupportedEncodingException e) {
  141. // The system should always have the platform default
  142. }
  143. return str;
  144. }
  145. /**
  146. * Translates a string into <code>application/x-www-form-urlencoded</code>
  147. * format using a specific encoding scheme. This method uses the
  148. * supplied encoding scheme to obtain the bytes for unsafe
  149. * characters.
  150. * <p>
  151. * <em><strong>Note:</strong> The <a href=
  152. * "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
  153. * World Wide Web Consortium Recommendation</a> states that
  154. * UTF-8 should be used. Not doing so may introduce
  155. * incompatibilites.</em>
  156. *
  157. * @param s <code>String</code> to be translated.
  158. * @param enc The name of a supported
  159. * <a href="../lang/package-summary.html#charenc">character
  160. * encoding</a>.
  161. * @return the translated <code>String</code>.
  162. * @exception UnsupportedEncodingException
  163. * If the named encoding is not supported
  164. * @see URLDecoder#decode(java.lang.String, java.lang.String)
  165. * @since 1.4
  166. */
  167. public static String encode(String s, String enc)
  168. throws UnsupportedEncodingException {
  169. boolean needToChange = false;
  170. boolean wroteUnencodedChar = false;
  171. int maxBytesPerChar = 10; // rather arbitrary limit, but safe for now
  172. StringBuffer out = new StringBuffer(s.length());
  173. ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
  174. OutputStreamWriter writer = new OutputStreamWriter(buf, enc);
  175. for (int i = 0; i < s.length(); i++) {
  176. int c = (int) s.charAt(i);
  177. //System.out.println("Examining character: " + c);
  178. if (dontNeedEncoding.get(c)) {
  179. if (c == ' ') {
  180. c = '+';
  181. needToChange = true;
  182. }
  183. //System.out.println("Storing: " + c);
  184. out.append((char)c);
  185. wroteUnencodedChar = true;
  186. } else {
  187. // convert to external encoding before hex conversion
  188. try {
  189. if (wroteUnencodedChar) { // Fix for 4407610
  190. writer = new OutputStreamWriter(buf, enc);
  191. wroteUnencodedChar = false;
  192. }
  193. writer.write(c);
  194. /*
  195. * If this character represents the start of a Unicode
  196. * surrogate pair, then pass in two characters. It's not
  197. * clear what should be done if a bytes reserved in the
  198. * surrogate pairs range occurs outside of a legal
  199. * surrogate pair. For now, just treat it as if it were
  200. * any other character.
  201. */
  202. if (c >= 0xD800 && c <= 0xDBFF) {
  203. /*
  204. System.out.println(Integer.toHexString(c)
  205. + " is high surrogate");
  206. */
  207. if ( (i+1) < s.length()) {
  208. int d = (int) s.charAt(i+1);
  209. /*
  210. System.out.println("\tExamining "
  211. + Integer.toHexString(d));
  212. */
  213. if (d >= 0xDC00 && d <= 0xDFFF) {
  214. /*
  215. System.out.println("\t"
  216. + Integer.toHexString(d)
  217. + " is low surrogate");
  218. */
  219. writer.write(d);
  220. i++;
  221. }
  222. }
  223. }
  224. writer.flush();
  225. } catch(IOException e) {
  226. buf.reset();
  227. continue;
  228. }
  229. byte[] ba = buf.toByteArray();
  230. for (int j = 0; j < ba.length; j++) {
  231. out.append('%');
  232. char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
  233. // converting to use uppercase letter as part of
  234. // the hex value if ch is a letter.
  235. if (Character.isLetter(ch)) {
  236. ch -= caseDiff;
  237. }
  238. out.append(ch);
  239. ch = Character.forDigit(ba[j] & 0xF, 16);
  240. if (Character.isLetter(ch)) {
  241. ch -= caseDiff;
  242. }
  243. out.append(ch);
  244. }
  245. buf.reset();
  246. needToChange = true;
  247. }
  248. }
  249. return (needToChange? out.toString() : s);
  250. }
  251. }