以下代码基本上可以按预期工作。然而,偏执,我想,为了避免资源泄漏,
HttpURLConnection.disconnect
用完后需要调用吗?- 我需要调用
InputStream.close
吗? - 我需要调用
InputStreamReader.close
吗? - 在构建httpUrlConnection之后是否需要有以下两行代码:
httpUrlConnection.setDoInput(true)
和httpUrlConnection.setDoOutput(false)
?
我之所以这么问,是因为我看到的大多数示例都没有进行此类清理。 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);
}
}
}
最佳答案
是的,您需要先关闭输入流,然后再关闭 httpconnection。根据 javadoc .
Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.
接下来两个问题的答案取决于您的连接目的。阅读本文link 了解更多详情。
关于android - 使用完毕后是否需要调用 HttpURLConnection.disconnect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11056088/