【问题标题】:Java Post Connection Using Try with ResourcesJava Post 连接使用 Try with Resources
【发布时间】:2016-10-19 05:45:20
【问题描述】:

我想使用资源尝试实现处理 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 是更好的方法吗?

【问题讨论】:

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


    【解决方案1】:

    试试这个。

    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()

    【讨论】:

    • 这对我的大多数查询都很好。但是,使用嵌套尝试是一种好方法吗?我的意思是我的代码在 try-catch-finally 上运行良好。这种方法有什么好处?
    • @Chinmayjain 如果您/某人复制粘贴代码,它将显示为一个整体块。
    • 优势在于可靠性。任何关闭都可能导致 IOException。您还可以将代码移动到私有方法(即 writeQuery 和 readResponse),这样看起来会更好;)
    【解决方案2】:

    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 有资源肯定会帮助你管理资源。但是,如果您确信在使用后可以正确释放资源,那么您的代码就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-18
      • 2013-07-21
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多