title: Read JSON message from HTTP POST request in Java
body: <p>I am new to Java and to client- server programming.</p>
  
  <p>I am using embedded Jetty, and I'm trying to send a JSON string to some address (<a href="http://localhost:7070/json" rel="nofollow">http://localhost:7070/json</a>) and then to display the JSON string in that address.</p>
  
  <p>I tried the following code but all I get is null.</p>
  
  <p>Embedded Jetty code:</p>
  
  <pre><code>public static void main(String[] args) throws Exception {
      Server server = new Server(7070);
      ServletContextHandler handler = new ServletContextHandler(server, "/json");
      handler.addServlet(ExampleServlet.class, "/");
      server.start();
  }
  </code></pre>
  
  <p>Client side function for sending the Http POST:</p>
  
  <pre><code>public static void sendHttp(){
      HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead 
  
      try {
          HttpPost request = new HttpPost("http://localhost:7070/json");
  
          JSONObject object = new JSONObject();
          try {
              object.put("name", "MyName");
              object.put("age", "26");
          } catch (Exception ex) {
              System.out.println("Error: " + ex.getMessage());
          }
  
          String message = object.toString();
          request.setEntity(new StringEntity(message, "UTF8"));
          request.setHeader("Content-type", "application/json");
  
          HttpResponse response = httpClient.execute(request);
  
          // handle response here...
      }catch (Exception ex) {
          // handle exception here
      } finally {
      }
  }
  </code></pre>
  
  <p>And Servlet functions:</p>
  
  <pre><code>public class ExampleServlet extends HttpServlet{
  
      @Override
      protected void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws ServletException, IOException {
          //System.out.println("test get\n");
          doPost(req, resp);
      }
  
      @Override
      protected void doPost(HttpServletRequest req, HttpServletResponse resp)
              throws ServletException, IOException {
          //System.out.println("test post\n");
          PrintWriter out = resp.getWriter();
          String json_str = req.getParameter("name");
          out.print(json_str);
      }
  }
  </code></pre>
  
  <p>I call the sendHttp() method from a test class, after running the embedded Jetty server code (if that matters).</p>