title: Java Servlet send form data to REST API
body: <p>I have a simple HTML form to send a request to a REST API.  It works well, when I submit, it sends the form data to API and displays the response in the browser.</p>
  <pre><code>&lt;form name=&quot;theForm&quot; action=&quot;localhost:8080/App/rest/consumeForm&quot; method=&quot;post&quot;&gt;
      &lt;input name=&quot;userName&quot; value=&quot;Bob Smith&quot; /&gt;&lt;br/&gt;
      &lt;input type=&quot;submit&quot; value=&quot;submit&quot;/&gt;
  &lt;/form&gt;
  </code></pre>
  <p>Browser shows:</p>
  <pre><code>{&quot;address&quot;: &quot;12 First St.&quot;, &quot;city&quot;: &quot;Toronto&quot;}
  </code></pre>
  <p>I would like to capture the response.  Any ideas?  (no ajax or javascript, just plain old Servlet or JSP please)</p>
  <p><strong>PART 2:</strong>
  I now POST my form to a servlet I created, which handles the request and response from the REST API.  It works nicely, but it needs the form data URLEncoded.  Anyone know if there is a way to convert form data to such a string, or even convert form data to JSON directly?</p>
  <pre><code>String charset = java.nio.charset.StandardCharsets.UTF_8.name();
  String userName = &quot;Bob Smith&quot;;
  String country = &quot;Canada&quot;;
  
  String queryString = String.format(&quot;userName=%s&amp;country=%s&quot; 
          ,URLEncoder.encode(userName, charset) 
          ,URLEncoder.encode(country, charset)            
          );
  </code></pre>
  <p><strong>Can I build the above queryString dynamically?</strong></p>
  <pre><code>//// send request
  URLConnection connection = new URL(&quot;localhost:8080/App/rest/consumeForm&quot;).openConnection();
  connection.setDoOutput(true); // Triggers POST.
  connection.setRequestProperty(&quot;Accept-Charset&quot;, charset);
  connection.setRequestProperty(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded;charset=&quot; + charset);
  try (OutputStream output = connection.getOutputStream()) {
      output.write(queryString.getBytes(charset));
  }       
  
  //// get response
  BufferedReader apiResponse = new BufferedReader(new InputStreamReader((connection.getInputStream())));
  String output;
  System.out.println(&quot;\n\n\nrecieved....&quot;);
  while ((output = apiResponse.readLine()) != null) {
      System.out.println(output);
  }
  </code></pre>