在jdk7之前,你必须用try{}finally{}在try内使用资源,在finally中关闭资源,不管try中的代码是否正常退出或者异常退出。jdk7之后,你可以不必要写finally语句来关闭资源,只要你在try()的括号内部定义要使用的资源,不用写一大堆finally来关闭资源。
所有实现Closeable的类声明都可以写在里面,最常见于流操作,socket操作,新版的httpclient也可以;需要注意的是,try()的括号中可以写多行声明,并且每个要关的资源对象要实现AutoCloseable接口,语句用分号隔开。
请看例子:
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;
}
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;
}
CloseableHttpClient 和CloseableHttpResponse 都实现了Closeable,而Closeable继承了AutoCloseable