1 /* 2 * Copyright (c) 1995, 2017, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.net; 27 28 import java.io.UnsupportedEncodingException; 29 import java.io.CharArrayWriter; 30 import java.nio.charset.Charset; 31 import java.nio.charset.IllegalCharsetNameException; 32 import java.nio.charset.UnsupportedCharsetException ; 33 import java.util.BitSet; 34 import java.util.Objects; 35 import sun.security.action.GetPropertyAction; 36 37 /** 38 * Utility class for HTML form encoding. This class contains static methods 39 * for converting a String to the <CODE>application/x-www-form-urlencoded</CODE> MIME 40 * format. For more information about HTML form encoding, consult the HTML 41 * <A HREF="http://www.w3.org/TR/html4/">specification</A>. 42 * 43 * <p> 44 * When encoding a String, the following rules apply: 45 * 46 * <ul> 47 * <li>The alphanumeric characters "{@code a}" through 48 * "{@code z}", "{@code A}" through 49 * "{@code Z}" and "{@code 0}" 50 * through "{@code 9}" remain the same. 51 * <li>The special characters "{@code .}", 52 * "{@code -}", "{@code *}", and 53 * "{@code _}" remain the same. 54 * <li>The space character " " is 55 * converted into a plus sign "{@code +}". 56 * <li>All other characters are unsafe and are first converted into 57 * one or more bytes using some encoding scheme. Then each byte is 58 * represented by the 3-character string 59 * "<i>{@code %xy}</i>", where <i>xy</i> is the 60 * two-digit hexadecimal representation of the byte. 61 * The recommended encoding scheme to use is UTF-8. However, 62 * for compatibility reasons, if an encoding is not specified, 63 * then the default encoding of the platform is used. 64 * </ul> 65 * 66 * <p> 67 * For example using UTF-8 as the encoding scheme the string "The 68 * string ü@foo-bar" would get converted to 69 * "The+string+%C3%BC%40foo-bar" because in UTF-8 the character 70 * ü is encoded as two bytes C3 (hex) and BC (hex), and the 71 * character @ is encoded as one byte 40 (hex). 72 * 73 * @author Herb Jellinek 74 * @since 1.0 75 */ 76 public class URLEncoder { 77 static BitSet dontNeedEncoding; 78 static final int caseDiff = ('a' - 'A'); 79 static String dfltEncName = null; 80 81 static { 82 83 /* The list of characters that are not encoded has been 84 * determined as follows: 85 * 86 * RFC 2396 states: 87 * ----- 88 * Data characters that are allowed in a URI but do not have a 89 * reserved purpose are called unreserved. These include upper 90 * and lower case letters, decimal digits, and a limited set of 91 * punctuation marks and symbols. 92 * 93 * unreserved = alphanum | mark 94 * 95 * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" 96 * 97 * Unreserved characters can be escaped without changing the 98 * semantics of the URI, but this should not be done unless the 99 * URI is being used in a context that does not allow the 100 * unescaped character to appear. 101 * ----- 102 * 103 * It appears that both Netscape and Internet Explorer escape 104 * all special characters from this list with the exception 105 * of "-", "_", ".", "*". While it is not clear why they are 106 * escaping the other characters, perhaps it is safest to 107 * assume that there might be contexts in which the others 108 * are unsafe if not escaped. Therefore, we will use the same 109 * list. It is also noteworthy that this is consistent with 110 * O'Reilly's "HTML: The Definitive Guide" (page 164). 111 * 112 * As a last note, Intenet Explorer does not encode the "@" 113 * character which is clearly not unreserved according to the 114 * RFC. We are being consistent with the RFC in this matter, 115 * as is Netscape. 116 * 117 */ 118 119 dontNeedEncoding = new BitSet(256); 120 int i; 121 for (i = 'a'; i <= 'z'; i++) { 122 dontNeedEncoding.set(i); 123 } 124 for (i = 'A'; i <= 'Z'; i++) { 125 dontNeedEncoding.set(i); 126 } 127 for (i = '0'; i <= '9'; i++) { 128 dontNeedEncoding.set(i); 129 } 130 dontNeedEncoding.set(' '); /* encoding a space to a + is done 131 * in the encode() method */ 132 dontNeedEncoding.set('-'); 133 dontNeedEncoding.set('_'); 134 dontNeedEncoding.set('.'); 135 dontNeedEncoding.set('*'); 136 137 dfltEncName = GetPropertyAction.privilegedGetProperty("file.encoding"); 138 } 139 140 /** 141 * You can't call the constructor. 142 */ URLEncoder()143 private URLEncoder() { } 144 145 /** 146 * Translates a string into {@code x-www-form-urlencoded} 147 * format. This method uses the platform's default encoding 148 * as the encoding scheme to obtain the bytes for unsafe characters. 149 * 150 * @param s {@code String} to be translated. 151 * @deprecated The resulting string may vary depending on the platform's 152 * default encoding. Instead, use the encode(String,String) 153 * method to specify the encoding. 154 * @return the translated {@code String}. 155 */ 156 @Deprecated encode(String s)157 public static String encode(String s) { 158 159 String str = null; 160 161 try { 162 str = encode(s, dfltEncName); 163 } catch (UnsupportedEncodingException e) { 164 // The system should always have the platform default 165 } 166 167 return str; 168 } 169 170 /** 171 * Translates a string into {@code application/x-www-form-urlencoded} 172 * format using a specific encoding scheme. 173 * <p> 174 * This method behaves the same as {@linkplain String encode(String s, Charset charset)} 175 * except that it will {@linkplain java.nio.charset.Charset#forName look up the charset} 176 * using the given encoding name. 177 * 178 * @param s {@code String} to be translated. 179 * @param enc The name of a supported 180 * <a href="../lang/package-summary.html#charenc">character 181 * encoding</a>. 182 * @return the translated {@code String}. 183 * @throws UnsupportedEncodingException 184 * If the named encoding is not supported 185 * @see URLDecoder#decode(java.lang.String, java.lang.String) 186 * @since 1.4 187 */ encode(String s, String enc)188 public static String encode(String s, String enc) 189 throws UnsupportedEncodingException { 190 if (enc == null) { 191 throw new NullPointerException("charsetName"); 192 } 193 194 try { 195 Charset charset = Charset.forName(enc); 196 return encode(s, charset); 197 } catch (IllegalCharsetNameException | UnsupportedCharsetException e) { 198 throw new UnsupportedEncodingException(enc); 199 } 200 } 201 202 /** 203 * Translates a string into {@code application/x-www-form-urlencoded} 204 * format using a specific {@linkplain java.nio.charset.Charset Charset}. 205 * This method uses the supplied charset to obtain the bytes for unsafe 206 * characters. 207 * <p> 208 * <em><strong>Note:</strong> The <a href= 209 * "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars"> 210 * World Wide Web Consortium Recommendation</a> states that 211 * UTF-8 should be used. Not doing so may introduce incompatibilities.</em> 212 * 213 * @param s {@code String} to be translated. 214 * @param charset the given charset 215 * @return the translated {@code String}. 216 * @throws NullPointerException if {@code s} or {@code charset} is {@code null}. 217 * @see URLDecoder#decode(java.lang.String, java.nio.charset.Charset) 218 * @since 10 219 */ encode(String s, Charset charset)220 public static String encode(String s, Charset charset) { 221 Objects.requireNonNull(charset, "charset"); 222 223 boolean needToChange = false; 224 StringBuilder out = new StringBuilder(s.length()); 225 CharArrayWriter charArrayWriter = new CharArrayWriter(); 226 227 for (int i = 0; i < s.length();) { 228 int c = (int) s.charAt(i); 229 //System.out.println("Examining character: " + c); 230 if (dontNeedEncoding.get(c)) { 231 if (c == ' ') { 232 c = '+'; 233 needToChange = true; 234 } 235 //System.out.println("Storing: " + c); 236 out.append((char)c); 237 i++; 238 } else { 239 // convert to external encoding before hex conversion 240 do { 241 charArrayWriter.write(c); 242 /* 243 * If this character represents the start of a Unicode 244 * surrogate pair, then pass in two characters. It's not 245 * clear what should be done if a byte reserved in the 246 * surrogate pairs range occurs outside of a legal 247 * surrogate pair. For now, just treat it as if it were 248 * any other character. 249 */ 250 if (c >= 0xD800 && c <= 0xDBFF) { 251 /* 252 System.out.println(Integer.toHexString(c) 253 + " is high surrogate"); 254 */ 255 if ( (i+1) < s.length()) { 256 int d = (int) s.charAt(i+1); 257 /* 258 System.out.println("\tExamining " 259 + Integer.toHexString(d)); 260 */ 261 if (d >= 0xDC00 && d <= 0xDFFF) { 262 /* 263 System.out.println("\t" 264 + Integer.toHexString(d) 265 + " is low surrogate"); 266 */ 267 charArrayWriter.write(d); 268 i++; 269 } 270 } 271 } 272 i++; 273 } while (i < s.length() && !dontNeedEncoding.get((c = (int) s.charAt(i)))); 274 275 charArrayWriter.flush(); 276 String str = new String(charArrayWriter.toCharArray()); 277 byte[] ba = str.getBytes(charset); 278 for (int j = 0; j < ba.length; j++) { 279 out.append('%'); 280 char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16); 281 // converting to use uppercase letter as part of 282 // the hex value if ch is a letter. 283 if (Character.isLetter(ch)) { 284 ch -= caseDiff; 285 } 286 out.append(ch); 287 ch = Character.forDigit(ba[j] & 0xF, 16); 288 if (Character.isLetter(ch)) { 289 ch -= caseDiff; 290 } 291 out.append(ch); 292 } 293 charArrayWriter.reset(); 294 needToChange = true; 295 } 296 } 297 298 return (needToChange? out.toString() : s); 299 } 300 } 301