Thursday, May 6, 2010

URL Encoding Decoding In Blackberry or J2ME

URLs often contains characters outside the ASCII set, the URL has to be converted to valid ASCII format using URL encoding which replaces unsafe ASCII characters with "%" followed by two hexadecimal digits corresponding to the character values in the ISO-8859-1 character-set.

Following is the code to achieve just that. It is tested with Blackberry but can be used in J2ME applications too.

class UrlEncoderDecoder
{
static final String HEX_DIGITS = "0123456789ABCDEF";


/**
* @param arrData The string to encode
* @return The URL-encoded string
*/
protected static String fnUrlEncode(byte[] arrData)
{
StringBuffer strResult = new StringBuffer();

for(int i = 0; i < arrData.length; i++)
{
char c = (char)arrData[i];

switch( c )
{
case '_':
case '.':
case '*':
case '-':
case '/':
{
strResult.append(c);
break;
}
case ' ':
{
strResult.append('+');
break;
}
default:
{
if((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9'))
{
strResult.append( c );
}
else
{
strResult.append('%');
strResult.append(HEX_DIGITS.charAt((c & 0xF0) >> 4 ));
strResult.append(HEX_DIGITS.charAt(c & 0x0F ));
}
}
}
} // for

return strResult.toString();
}

/**
* @param arrData The byte array containing the bytes of the string
* @return A decoded String
*/
protected static String fnUrlDecode(byte[] arrData)
{
String strDecodedData = "";

if(null != arrData)
{
byte[] arrDecodeBytes = new byte[arrData.length];

int nDecodedByteCount = 0;

try
{
for(int i = 0; i < arrData.length; i++ )
{
switch(arrData[i])
{
case '+':
{
arrDecodeBytes[nDecodedByteCount++] = (byte) ' ';
break ;
}
case '%':
{
arrDecodeBytes[nDecodedByteCount++] = (byte)((HEX_DIGITS.indexOf(arrData[++i]) << 4) +
(HEX_DIGITS.indexOf(arrData[++i])) );
break ;
}
default:
{
arrDecodeBytes[nDecodedByteCount++] = arrData[i];
}
}
}

strDecodedData = new String(arrDecodeBytes, 0, nDecodedByteCount) ;
}
catch(Exception e)
{
}
}

return strDecodedData;
}
}

No comments: