title: Java Post Connection Using Try with Resources
body: <p>I want to implement the code for handling POST requests using try with resources.</p>
  
  <p>Following is my code:</p>
  
  <pre><code>public static String sendPostRequestDummy(String url, String queryString) {
      log.info("Sending 'POST' request to URL : " + url);
      log.info("Data : " + queryString);
      BufferedReader in = null;
      HttpURLConnection con = null;
      StringBuilder response = new StringBuilder();
      try{
          URL obj = new URL(url);
          con = (HttpURLConnection) obj.openConnection();
          // add request header
          con.setRequestMethod("POST");
          con.setRequestProperty("User-Agent", "Mozilla/5.0");
          con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
          con.setRequestProperty("Content-Type", "application/json");
          // Send post request
          con.setDoOutput(true);
          DataOutputStream wr = new DataOutputStream(con.getOutputStream());
          wr.writeBytes(queryString);
          wr.flush();
          wr.close();
          int responseCode = con.getResponseCode();
          log.info("Response Code : " + responseCode);
          if (responseCode &gt;= 400)
              in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
          else 
              in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  
          String inputLine;
  
          while ((inputLine = in.readLine()) != null) {
              response.append(inputLine);
          }
      }catch(Exception e){
          log.error(e.getMessage(), e);
          log.error("Error during posting request");
      }
      finally{
          closeConnectionNoException(in,con);
      }
      return response.toString();
  }
  </code></pre>
  
  <p>I have the following concerns for the code:</p>
  
  <ol>
  <li>How to introduce conditional statements in try with resources for the above scenario?</li>
  <li>Is there a way to pass on the connection in try with resources? (It can be done using nested try-catch blocks since URL and HTTPConnection is not AutoCloseable, which itself is not a compliant solution)</li>
  <li>Is using try with resources for the above problem is a better approach?</li>
  </ol>