5252 */
5353public class URLCodec implements BinaryEncoder , BinaryDecoder , StringEncoder , StringDecoder {
5454
55+ /**
56+ * Radix used in encoding and decoding.
57+ */
58+ private static final int RADIX = 16 ;
59+
5560 /**
5661 * The default charset used for string decoding and encoding. Consider this field final. The next major release may
5762 * break compatibility and make this field be final.
@@ -138,9 +143,9 @@ public static final byte[] encodeUrl(BitSet urlsafe, byte[] bytes)
138143 } else {
139144 buffer .write ('%' );
140145 char hex1 = Character .toUpperCase (
141- Character .forDigit ((b >> 4 ) & 0xF , 16 ));
146+ Character .forDigit ((b >> 4 ) & 0xF , RADIX ));
142147 char hex2 = Character .toUpperCase (
143- Character .forDigit (b & 0xF , 16 ));
148+ Character .forDigit (b & 0xF , RADIX ));
144149 buffer .write (hex1 );
145150 buffer .write (hex2 );
146151 }
@@ -158,36 +163,37 @@ public static final byte[] encodeUrl(BitSet urlsafe, byte[] bytes)
158163 * @return array of original bytes
159164 * @throws DecoderException Thrown if URL decoding is unsuccessful
160165 */
161- public static final byte [] decodeUrl (byte [] bytes )
162- throws DecoderException
163- {
166+ public static final byte [] decodeUrl (byte [] bytes ) throws DecoderException {
164167 if (bytes == null ) {
165168 return null ;
166169 }
167- ByteArrayOutputStream buffer = new ByteArrayOutputStream ();
170+ ByteArrayOutputStream buffer = new ByteArrayOutputStream ();
168171 for (int i = 0 ; i < bytes .length ; i ++) {
169172 int b = bytes [i ];
170173 if (b == '+' ) {
171174 buffer .write (' ' );
172175 } else if (b == '%' ) {
173176 try {
174- int u = Character .digit ((char )bytes [++i ], 16 );
175- int l = Character .digit ((char )bytes [++i ], 16 );
176- if (u == -1 || l == -1 ) {
177- throw new DecoderException ("Invalid URL encoding" );
178- }
179- buffer .write ((char )((u << 4 ) + l ));
177+ int u = toCharacterDigit (bytes [++i ]);
178+ int l = toCharacterDigit (bytes [++i ]);
179+ buffer .write ((char ) ((u << 4 ) + l ));
180180 } catch (ArrayIndexOutOfBoundsException e ) {
181- throw new DecoderException ("Invalid URL encoding" );
181+ throw new DecoderException ("Invalid URL encoding: " );
182182 }
183183 } else {
184184 buffer .write (b );
185185 }
186186 }
187- return buffer .toByteArray ();
187+ return buffer .toByteArray ();
188188 }
189189
190-
190+ private static int toCharacterDigit (byte b ) throws DecoderException {
191+ int i = Character .digit ((char ) b , RADIX );
192+ if (i == -1 ) {
193+ throw new DecoderException ("Invalid URL encoding: not a valid digit (radix " + RADIX + "): " + b );
194+ }
195+ return i ;
196+ }
191197 /**
192198 * Encodes an array of bytes into an array of URL safe 7-bit
193199 * characters. Unsafe characters are escaped.
0 commit comments