title: Encoding/decoding REST path parameters
body: <p>I am trying to find the best way of getting round a design flaw in a web app I'm helping to support. One part of the service passes a parameter ("myparam") to a .jsp page, which in turn calls a REST service including our myparam as a path parameter. The design flaw bit is that myparam should be passed as a form parameter, since it can be free text. However, we cannot change the implementation as other parties are involved at the .jsp end of things.</p>
  
  <p>My solution was to encode the myparam using hex encoding (url encoding alone doesn't work as you end up with "%" etc. which the org.restlet implementation of REST doesn't like seeing in path parameters). Using the Apache codec library, I have something like this:</p>
  
  <p><strong>Option 1 (just hex):</strong></p>
  
  <pre><code>String decodedParam = new String(Hex.decodeHex(myparam.toCharArray()));
  </code></pre>
  
  <p>which works for our purposes. What I really wanted to do was to combine URL- and Hex-encoding, so that I can really cover all posibilities:</p>
  
  <p><strong>Option 2 (hex + url-decoding):</strong></p>
  
  <p>Parameter preparation:</p>
  
  <pre><code>String workText = URLEncoder.encode(inText, encoding); // a
  char[] encodedBytes = Hex.encodeHex(workText.getBytes()); // b
  String myparam = new String(encodedBytes);
  </code></pre>
  
  <p>Decoding (REST):</p>
  
  <pre><code>String decodedParam = new String(Hex.decodeHex(myparam.toCharArray())); // c
  String doubleDecodedParam = URLDecoder.decode(decodedParam, "UTF-8"); // d
  </code></pre>
  
  <p>I have two questions:</p>
  
  <ol>
  <li><p>why doesn't the second option work? (whenever I try and URL-decode my string at d) I get a java.lang.IllegalArgumentException). I've tested the double-encoding-and-decoding of my parameter values at <a href="http://ostermiller.org/calc/encode.html" rel="nofollow noreferrer">http://ostermiller.org/calc/encode.html</a> without problem.</p></li>
  <li><p>is there a better way to encode path parameters with REST?</p></li>
  </ol>