Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Helper Class: URLDecoder

Before we discuss the implementation of FormDataToXML.class, which is the main transformation component, we must discuss a helper class URLDecoder, which is used to process the URLEncoded values in the Query String, as was discussed earlier.

/**
 * URLDecoder
 *
 * @Author Jasmit Singh Kochhar
 *
 * @Date Created 08/2001
 *
 * @Purpose This class is used to decode URLencoded strings. 
 * Turns x-www-form-urlencoded format Strings into a standard 
 * string of text.
 *      
 */

import java.io.ByteArrayOutputStream;

public class URLDecoder {

static byte	hex_conversion[] = null;
static
    {
    hex_conversion = new byte[256];
    int i;
    byte j;

    for ( i = 0; i < 256; i++ )
       hex_conversion[i] = 0;

    for ( i='0', j=0; i <= '9';i++,j++ )
       hex_conversion[i] = j;

    for ( i='A', j=10; i <= 'F';i++,j++ )
            hex_conversion[i] = j;

    for ( i='a', j=10; i <= 'f';i++,j++ )
            hex_conversion[i] = j;
    }

private URLDecoder() { }

/**
 * Method: decode
 *
 * @Purpose Translates x-www-form-urlencoded formatted String 
 * into a standard String.
 * @param s String to be translated
 * @return the translated String.
 */

public static String decode(String s)
{
if ( s == null ) return s;

ByteArrayOutputStream out = new ByteArrayOutputStream(s.length());

int   hex_mode = 0;
int   nibble_storage = 0;
for_loop:
for (int i = 0; i < s.length(); i++)
{    char c = s.charAt(i);
    switch(hex_mode)
    {
    case 0:
     if (c == '%')
     { hex_mode = 1;	// get high nibble
     continue for_loop;
     }
     if (c == '+')
      c = ' ';
      break;
    case 1:
      nibble_storage = hex_conversion[c] << 4;
      hex_mode = 2;
      continue for_loop;
    case 2:
      c = (char) (nibble_storage | (0xf & hex_conversion[c]));
      hex_mode = 0;
      break;
    }
    out.write(c);
 }
return out.toString();
}
}
  • + Share This
  • 🔖 Save To Your Account