使用Try with Resources进行Java Post连接

Chi*_*ain 0 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();
}
Run Code Online (Sandbox Code Playgroud)

我对代码有以下顾虑:

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

sak*_*029 8

试试这个.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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