1. /*
  2. * @(#)URLDecoder.java 1.3 01/11/29
  3. *
  4. * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.net;
  8. import java.io.*;
  9. /**
  10. * The class contains a utility method for converting from
  11. * a MIME format called "<code>x-www-form-urlencoded</code>"
  12. * to a <code>String</code>
  13. * <p>
  14. * To convert to a <code>String</code>, each character is examined in turn:
  15. * <ul>
  16. * <li>The ASCII characters '<code>a</code>' through '<code>z</code>',
  17. * '<code>A</code>' through '<code>Z</code>', and '<code>0</code>'
  18. * through '<code>9</code>' remain the same.
  19. * <li>The plus sign '<code>+</code>'is converted into a
  20. * space character '<code> </code>'.
  21. * <li>The remaining characters are represented by 3-character
  22. * strings which begin with the percent sign,
  23. * "<code>%<i>xy</i></code>", where <i>xy</i> is the two-digit
  24. * hexadecimal representation of the lower 8-bits of the character.
  25. * </ul>
  26. *
  27. * @author Mark Chamness
  28. * @author Michael McCloskey
  29. * @version 1.3 11/29/01
  30. * @since JDK1.2
  31. */
  32. public class URLDecoder {
  33. public static String decode(String s) throws Exception {
  34. StringBuffer sb = new StringBuffer();
  35. for(int i=0; i<s.length(); i++) {
  36. char c = s.charAt(i);
  37. switch (c) {
  38. case '+':
  39. sb.append(' ');
  40. break;
  41. case '%':
  42. try {
  43. sb.append((char)Integer.parseInt(
  44. s.substring(i+1,i+3),16));
  45. }
  46. catch (NumberFormatException e) {
  47. throw new IllegalArgumentException();
  48. }
  49. i += 2;
  50. break;
  51. default:
  52. sb.append(c);
  53. break;
  54. }
  55. }
  56. // Undo conversion to external encoding
  57. String result = sb.toString();
  58. byte[] inputBytes = result.getBytes("8859_1");
  59. return new String(inputBytes);
  60. }
  61. }