title: POST request send JSON data Java HttpUrlConnection
body: <p>I have developed a Java code that convert the following cURL to java code using URL and HttpUrlConnection.
  the cURL is :</p>
  <pre><code>curl -i 'http://url.com' -X POST -H &quot;Content-Type: application/json&quot; -H &quot;Accept: application/json&quot; -d '{&quot;auth&quot;: { &quot;passwordCredentials&quot;: {&quot;username&quot;: &quot;adm&quot;, &quot;password&quot;: &quot;pwd&quot;},&quot;tenantName&quot;:&quot;adm&quot;}}'
  </code></pre>
  <p>I have written this code but it always gives HTTP code 400 bad request. I couldn't find what is missing.</p>
  <pre><code>String url=&quot;http://url.com&quot;;
  URL object=new URL(url);
  
  HttpURLConnection con = (HttpURLConnection) object.openConnection();
  con.setDoOutput(true);
  con.setDoInput(true);
  con.setRequestProperty(&quot;Content-Type&quot;, &quot;application/json&quot;);
  con.setRequestProperty(&quot;Accept&quot;, &quot;application/json&quot;);
  con.setRequestMethod(&quot;POST&quot;);
  
  JSONObject cred   = new JSONObject();
  JSONObject auth   = new JSONObject();
  JSONObject parent = new JSONObject();
  
  cred.put(&quot;username&quot;,&quot;adm&quot;);
  cred.put(&quot;password&quot;, &quot;pwd&quot;);
  
  auth.put(&quot;tenantName&quot;, &quot;adm&quot;);
  auth.put(&quot;passwordCredentials&quot;, cred.toString());
  
  parent.put(&quot;auth&quot;, auth.toString());
  
  OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
  wr.write(parent.toString());
  wr.flush();
  
  //display what returns the POST request
  
  StringBuilder sb = new StringBuilder();  
  int HttpResult = con.getResponseCode(); 
  if (HttpResult == HttpURLConnection.HTTP_OK) {
      BufferedReader br = new BufferedReader(
              new InputStreamReader(con.getInputStream(), &quot;utf-8&quot;));
      String line = null;  
      while ((line = br.readLine()) != null) {  
          sb.append(line + &quot;\n&quot;);  
      }
      br.close();
      System.out.println(&quot;&quot; + sb.toString());  
  } else {
      System.out.println(con.getResponseMessage());  
  }  
  </code></pre>