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