title: POST request to REST API with JSON object as payload
body: <p>I am trying to get the JSON response from the REST API using the POST request that has JSON payload (should be converted to URL encoded text before sending). I have followed some tutorials to implement the process but I get error with status code 400. I may not be encoding the given JSON string or missing something. Please help me solve this problem. Thanks.</p>
  
  <p>Here is my code</p>
  
  <pre><code>    try {
          URL url = new URL("https://appem.totango.com/api/v1/search/accounts/health_dist");
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setDoOutput(true);
          conn.setRequestMethod("POST");
          conn.setRequestProperty("Content-Type", "application/json");
          conn.setRequestProperty("app-token", "1a1c626e8cdca0a80ae61b73ee0a1909941ab3d7mobile+testme@totango.com");
          conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
          conn.setRequestProperty("X-Requested-With","XMLHttpRequest");
  
          String payload = "{\"terms\":[{\"type\":\"totango_user_scope\",\"is_one_of\":[\"mobile+testme@totango.com\"]}],\"group_fields\":[{\"type\":\"health\"}]}";
  
          OutputStream os = conn.getOutputStream();
          os.write(payload.getBytes());
          os.flush();
  
          if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
              throw new RuntimeException("Failed : HTTP error code : "
                      + conn.getResponseCode());
          }
  
          BufferedReader br = new BufferedReader(new InputStreamReader(
                  (conn.getInputStream())));
  
          String output;
          System.out.println("Output from Server .... \n");
          while ((output = br.readLine()) != null) {
              System.out.println(output);
          }
          conn.disconnect();
      } catch (MalformedURLException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
  </code></pre>