线上代码,如何正确的关闭BufferedReader流。我用的JDK1.7
原来的代码如下:
public static String httpPostWithJson(String ecUrl, String params) {
try {
// 创建连接
URL url = new URL(ecUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
// POST请求
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(params);
out.flush();
out.close();
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
// System.out.println(sb);
reader.close();
// 断开连接
connection.disconnect();
return sb.toString();
} catch (MalformedURLException e) {
logger.error("httpPostWithJsonMalformedURLException error", e);
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
logger.error("httpPostWithJsonUnsupportedEncodingException error", e);
e.printStackTrace();
} catch (IOException e) {
logger.error("httpPostWithJsonIOException error", e);
e.printStackTrace();
}
return null;
}
这样虽然在finally中关闭了流,但是又要在finally中引入IOException,这样是不是很麻烦啊
关于关闭流,还有没有好的措施或者实践经验呢?
谢谢~~
补充:JDK 1.7但是不能用Try-with-resources机制
千巷猫影
aluckdog
翻过高山走不出你
相关分类