URLEncoderpublic class URLEncoder extends Object This class is used to encode a string using the format required by
{@code application/x-www-form-urlencoded} MIME content type. |
Fields Summary |
---|
static final String | digits |
Constructors Summary |
---|
private URLEncoder()Prevents this class from being instantiated. //$NON-NLS-1$
|
Methods Summary |
---|
private static void | convert(java.lang.String s, java.lang.StringBuffer buf, java.lang.String enc)
byte[] bytes = s.getBytes(enc);
for (int j = 0; j < bytes.length; j++) {
buf.append('%");
buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
buf.append(digits.charAt(bytes[j] & 0xf));
}
| public static java.lang.String | encode(java.lang.String s)Encodes a given string {@code s} in a x-www-form-urlencoded string using
the specified encoding scheme {@code enc}.
All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
and characters '.', '-', '*', '_' are converted into their hexadecimal
value prepended by '%'. For example: '#' -> %23. In addition, spaces are
substituted by '+'
StringBuffer buf = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if ((ch >= 'a" && ch <= 'z") || (ch >= 'A" && ch <= 'Z")
|| (ch >= '0" && ch <= '9") || ".-*_".indexOf(ch) > -1) { //$NON-NLS-1$
buf.append(ch);
} else if (ch == ' ") {
buf.append('+");
} else {
byte[] bytes = new String(new char[] { ch }).getBytes();
for (int j = 0; j < bytes.length; j++) {
buf.append('%");
buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
buf.append(digits.charAt(bytes[j] & 0xf));
}
}
}
return buf.toString();
| public static java.lang.String | encode(java.lang.String s, java.lang.String enc)Encodes the given string {@code s} in a x-www-form-urlencoded string
using the specified encoding scheme {@code enc}.
All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
and characters '.', '-', '*', '_' are converted into their hexadecimal
value prepended by '%'. For example: '#' -> %23. In addition, spaces are
substituted by '+'
if (s == null || enc == null) {
throw new NullPointerException();
}
// check for UnsupportedEncodingException
"".getBytes(enc); //$NON-NLS-1$
StringBuffer buf = new StringBuffer();
int start = -1;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if ((ch >= 'a" && ch <= 'z") || (ch >= 'A" && ch <= 'Z")
|| (ch >= '0" && ch <= '9") || " .-*_".indexOf(ch) > -1) { //$NON-NLS-1$
if (start >= 0) {
convert(s.substring(start, i), buf, enc);
start = -1;
}
if (ch != ' ") {
buf.append(ch);
} else {
buf.append('+");
}
} else {
if (start < 0) {
start = i;
}
}
}
if (start >= 0) {
convert(s.substring(start, s.length()), buf, enc);
}
return buf.toString();
|
|