|
Encode URL
by Jason Lam
When making HTTP calls you may need to encode the parameters because certains characters will cause problems usually the "space" is the prime suspect i.e.:
http://www.somedomain.com/changeAddress?
address=18394 West Wood Drive
should be
http://www.somedomain.com/changeAddress?
address=18394%20West%20Wood%20Drive
See the following for a reference of all the characters http://www.w3schools.com/html/html_ref_urlencode.asp, for more information on URL encoding specification see the RFC 1738 section 2.2 http://www.faqs.org/rfcs/rfc1738.html
The following code snippet will help you encode the url parameters:
public final static String encodeURL(String url) {
String newurl = "";
int urllen = url.length();
for(int i = 0; i < urllen; ++i) {
char c = url.charAt(i);
if(((c >= 'a') && (c <= 'z'))
|| ((c >= 'A') && (c <= 'Z'))
|| ((c >= '0') && (c <= '9'))
|| (c == '.') || (c == '-')
|| (c == '*') || (c == '_')
|| (c == '/') || (c == '~')) {
newurl += c;
}
else if(c == ' ') {
newurl += '+';
}
else {
newurl += encodeChar(c);
}
}
return newurl;
}
private static String encodeChar(char c) {
String encchar = "%";
encchar += Integer.toHexString((c / 16) % 16).toUpperCase();
encchar += Integer.toHexString(c % 16).toUpperCase();
return encchar;
}
|