[ Back | Previous | Next ]

How to create URLDecoder (opposit of java.net.URLEncoder)

Package:
java.net.*
Product:
JDK
Release:
1.0.2
Related Links:
General
URLConnection
URLDecoder
Comment:
/** A URI class is a collection of methods that process URLs
**/

package nl.rotterdam.port.net;
import java.net.*;

public class URLDecoder  {
  /**
   * You can't call the constructor.
   */
  private URLDecoder() { }

  private static char x2c(char [] what) {
    int digit;

    digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) -'A')+10 : (what[0] - '0'));
    digit *= 16;
    digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
    return (char)digit;
  }

  /**
   * Translates String into x-www-form-urlencoded format.
   * @param s String to be translated
   * @return the translated String.
   */
  public static String decode(String uri) {
    boolean badesc = false;
    boolean badpath = false;
    String unescaped = "";
    String hexstring = null;
    Character ch;

    uri = uri.replace('+',' ');
    for (int y=0; y < uri.length(); y++) {
      if (uri.charAt(y) != '%') {
        unescaped += uri.charAt(y);
        //System.out.print( uri.charAt(y));
      } else {
        hexstring = uri.substring(y+1,y+3);
        y+=2;
        unescaped += x2c( hexstring.toCharArray() );
        //System.out.println("HexString " + hexstring + ", value " + x2c( hexstring.toCharArray()));
      }
      //System.out.println("Total uri: " + unescaped);
    }
    //System.out.println("\nTotal uri: " + unescaped);
    return unescaped;
  }

  /**
   * Translates String into x-www-form-urlencoded format.
   * @param s String to be translated
   * @return the translated String.
   */
   public static String encode(String s) {
    return URLEncoder.encode(s);
   }
}
1