title: servlet request parameter character encoding
body: <p>I have a Java servlet that receives data from an upstream system via a HTTP GET request. This request includes a parameter named "text". If the upstream system sets this parameter to:</p>
  
  <pre><code>TEST3 please ignore:
  </code></pre>
  
  <p>It appears in the logs of the upstream system as:</p>
  
  <pre><code>00 54 00 45 00 53 00 54 00 33 00 20 00 70 00 6c   //TEST3 pl
  00 65 00 61 00 73 00 65 00 20 00 69 00 67 00 6e   //ease ign
  00 6f 00 72 00 65 00 3a                           //ore:   
  </code></pre>
  
  <p>(The // comments do not actually appear in the logs)</p>
  
  <p>In my servlet I read this parameter with:</p>
  
  <pre><code>String text = request.getParameter("text");
  </code></pre>
  
  <p>If I print the value of <code>text</code> to the console, it appears as:</p>
  
  <pre><code>T E S T 3  p l e a s e  i g n o r e :
  </code></pre>
  
  <p>If I inspect the value of <code>text</code> in the debugger, it appears as:</p>
  
  <pre><code>\u000T\u000E\u000S\u000T\u0003\u0000 \u000p\u000l\u000e\u000a\u000s\u000e\u0000 
  \u000i\u000g\u000n\u000o\u000r\u000e\u000:
  </code></pre>
  
  <p>So it seems that there's a problem with the character encoding. The upstream system is supposed to use UTF-16. My guess is that the servlet is assuming UTF-8 and therefore is reading twice the number of characters it should be. For the message "TEST3 please ignore:" the first byte of each character is <code>00</code>. This is being interpreted as a space when read by the servlet, which explains the space that appears before each character when the message is logged by the servlet.</p>
  
  <p>Obviously my goal is simply to get the message "TEST3 please ignore:" when I read the <code>text</code> request param. My guess is that I could achieve this by specifying the character encoding of the request parameter, but I don't know how to do this.</p>