使用资源尝试进行Java Post Connection

时间:2016-10-19 05:45:20

标签: java exception-handling try-catch try-with-resources

我想使用try with resources来实现处理POST请求的代码。

以下是我的代码:

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 >= 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();
}

我对代码有以下顾虑:

  1. 如何在针对上述场景的资源中引入条件语句?
  2. 有没有办法在资源中尝试传递连接? (可以使用嵌套的try-catch块来完成,因为URL和HTTPConnection不是AutoCloseable,它本身不是兼容的解决方案)
  3. 使用try with resources来解决上述问题是一种更好的方法吗?

2 个答案:

答案 0 :(得分:7)

试试这个。

HttpURLConnection con = (HttpURLConnection) obj.openConnection();
try (AutoCloseable conc = () -> con.disconnect()) {
    // add request headers
    try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
        wr.writeBytes(queryString);
    }
    int responseCode = con.getResponseCode();
    try (InputStream ins = responseCode >= 400 ? con.getErrorStream() : con.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(ins))) {
        // receive response
    }
}

() -> con.disconnect()是一个lambda表达式,它在try语句的最后阶段执行con.disconnect()

答案 1 :(得分:0)

1:您也可以在try内使用带有资源语句的条件语句。不幸的是,您必须为此块定义新变量,并且不能使用预定义变量。 (代码中的变量in

try (BufferedReader in = (responseCode >= 400 ? new BufferedReader(new InputStreamReader(con.getErrorStream())) : new BufferedReader(new InputStreamReader(con.getInputStream())))) {
   // your code for getting string data
}

2:我不确定HttpUrlConnectionAutoCloseable,所以自己打电话给disconnect()可能是个好主意。我对这一点有任何建议。

3:try资源肯定会帮助您管理资源。但是,如果您确信在使用后正确释放资源,那么您的代码就可以了。