Sunday, February 10, 2008

Url Encode function. Encode a string according to W3C standards

this is a function that turns all the chars in a string to the W3C Standards. 
/**
* Encode a string according to W3C standards.
*
*/

public static String urlEncoder(String s) {
if (s == null)
return s;
StringBuffer sb = new StringBuffer(s.length() * 3);
try {
char c;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (c == '&') {
sb.append("&amp;");
} else if (c == ' ') {
sb.append('+');
} else if (
(c >= ',' && c <= ';')
(c >= 'A' && c <= 'Z')
(c >= 'a' && c <= 'z')
c == '_'
c == '?') {
sb.append(c);
} else {
sb.append('%');
if (c > 15) { // is it a non-control char, ie. >x0F so 2 chars
sb.append(Integer.toHexString((int)c)); // just add % and the string
} else {
sb.append("0" + Integer.toHexString((int)c));
// otherwise need to add a leading 0
}
}
}

} catch (Exception ex) {
return (null);
}
return (sb.toString());
}
 
source of this function : http://forum.java.sun.com/thread.jspa?threadID=594204&messageID=3596899

1 comment:

Anonymous said...

The author of byramix.blogspot.com has written an excellent article. You have made your point and there is not much to argue about. It is like the following universal truth that you can not argue with: The people who are actually going to be interesting aren't going to give you meaningful answers to a/s/l anyway. Thanks for the info.