title: Java httpserver crashes upon receiving POST requests
body: <p>I am trying to write a simple HTTP server in Java that can handle POST requests.  While my server successfully receives the GET, it crashes on the POST.  </p>
  
  <p>Here is the server</p>
  
  <pre><code>public class RequestHandler {
      public static void main(String[] args) throws Exception {
          HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
          server.createContext("/requests", new MyHandler());
          server.setExecutor(null); // creates a default executor
          server.start();
      }
  
      static class MyHandler implements HttpHandler {
          public void handle(HttpExchange t) throws IOException {
              String response = "hello world";
              t.sendResponseHeaders(200, response.length());
              System.out.println(response);
              OutputStream os = t.getResponseBody();
              os.write(response.getBytes());
              os.close();
          }
      }
  }
  </code></pre>
  
  <p>And here is the Java code I use to send the POST</p>
  
  <pre><code>// HTTP POST request
  private void sendPost() throws Exception {
  
      String url = "http://localhost:8080/requests";
      URL obj = new URL(url);
      HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
  
      //add reuqest header
      con.setRequestMethod("POST");
      con.setRequestProperty("User-Agent", USER_AGENT);
      con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  
      String urlParameters = "sn=C02G8416DRJM&amp;cn=&amp;locale=&amp;caller=&amp;num=12345";
  
      // Send post request
      con.setDoOutput(true);
      DataOutputStream wr = new DataOutputStream(con.getOutputStream());
      wr.writeBytes(urlParameters);
      wr.flush();
      wr.close();
  
      int responseCode = con.getResponseCode();
      System.out.println("\nSending 'POST' request to URL : " + url);
      System.out.println("Post parameters : " + urlParameters);
      System.out.println("Response Code : " + responseCode);
  
      BufferedReader in = new BufferedReader(
              new InputStreamReader(con.getInputStream()));
      String inputLine;
      StringBuffer response = new StringBuffer();
  
      while ((inputLine = in.readLine()) != null) {
          response.append(inputLine);
      }
      in.close();
  
      //print result
      System.out.println(response.toString());
  }
  </code></pre>
  
  <p>Each time the POST request crashes on this line</p>
  
  <pre><code>HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
  </code></pre>
  
  <p>but when I change the URL to the one provided in the example where I found this it works.</p>