以下代码基本上按预期工作。但是,要偏执,我想知道,为了避免资源泄漏,
HttpURLConnection.disconnect
使用完毕后需要打电话吗?- 我需要打电话
InputStream.close
吗? - 我需要打电话
InputStreamReader.close
吗? - 我是否需要有以下 2 行代码:
httpUrlConnection.setDoInput(true)
并且httpUrlConnection.setDoOutput(false)
,在构建 httpUrlConnection 之后?
我之所以这么问,是因为我看到的大多数示例都没有进行此类清理。http://www.exampledepot.com/egs/java.net/post.html和http://www.vogella.com/articles/AndroidNetworking/article.html。我只是想确保这些示例也是正确的。
public static String getResponseBodyAsString(String request) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(request);
HttpURLConnection httpUrlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpUrlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
int charRead = 0;
char[] buffer = new char[1024];
StringBuffer stringBuffer = new StringBuffer();
while ((charRead = bufferedReader.read(buffer)) > 0) {
stringBuffer.append(buffer, 0, charRead);
}
return stringBuffer.toString();
} catch (MalformedURLException e) {
Log.e(TAG, "", e);
} catch (IOException e) {
Log.e(TAG, "", e);
} finally {
close(bufferedReader);
}
return null;
}
private static void close(Reader reader) {
if (reader != null) {
try {
reader.close();
} catch (IOException exp) {
Log.e(TAG, "", exp);
}
}
}