The try(){} syntax in java closes resources

Before jdk7, you must use try{}finally{} to use resources in try and close resources in finally, regardless of whether the code in the try exits normally or abnormally. After jdk7, you don't need to write a finally statement to close the resource, as long as you define the resource to be used inside the try() brackets, you don't need to write a lot of finally to close the resource.

All the class declarations that implement Closeable can be written in it, the most common are stream operations, socket operations, and the new version of httpclient; it should be noted that multiple lines of declarations can be written in the parentheses of try(), and each one needs to be closed. The resource object must implement the AutoCloseable interface, and the statements are separated by semicolons.

Please see the example:

Before jdk7:

 /**
     * 发送 GET 请求(HTTP),无参数
     *
     * @param url
     * @return
     */
    public static String doGet(String url) {
    
    
        if (StringUtils.isBlank(url)) {
    
    
            return "url不能为空";
        }
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建http GET请求
        logger.info("url:{}", url);
        HttpGet httpGet = new HttpGet(url);
        // 设置请求和传输超时时间
        httpGet.setConfig(requestConfig);
        // 执行请求
        CloseableHttpResponse response = null;
        String result = "";
        try {
    
    
            response = httpclient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
    
    
                result = EntityUtils.toString(response.getEntity(), chaset);
                logger.info("HttpGet方式请求成功!返回结果:{}", result);
            } else {
    
    
                logger.info("HttpGet方式请求失败!状态码:" + statusCode);
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (response != null) {
    
    
                try {
    
    
                    response.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
            try {
    
    
                httpclient.close();//相当于关闭浏览器
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        return result;
    }

After jdk7:

/**
     * 发送 GET 请求(HTTP),无参数
     * @param url
     * @return
     */
    public static String doGet(String url) {
    
    
        if (StringUtils.isBlank(url)) {
    
    
            return "url不能为空";
        }
        // 创建http GET请求
        logger.info("url:{}", url);
        HttpGet httpGet = new HttpGet(url);
        // 设置请求和传输超时时间
        httpGet.setConfig(requestConfig);
        String result = "";
        try (CloseableHttpClient httpclient = HttpClients.createDefault();// 创建Httpclient对象
             CloseableHttpResponse response = httpclient.execute(httpGet);// 执行请求
        ) {
    
    
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
    
    
                result = EntityUtils.toString(response.getEntity(), chaset);
                logger.info("HttpGet方式请求成功!返回结果:{}", result);
            } else {
    
    
                logger.info("HttpGet方式请求失败!状态码:" + statusCode);
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return result;
    }

Both CloseableHttpClient and CloseableHttpResponse implement Closeable, and Closeable inherits AutoCloseable

Guess you like

Origin blog.csdn.net/qq_33697094/article/details/110872177