以下代码基本上按预期工作.然而,为了偏执,我想知道,为了避免资源泄漏,
HttpURLConnection.disconnect完成使用后我需要打电话吗?InputStream.close吗?InputStreamReader.close吗?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) …Run Code Online (Sandbox Code Playgroud) android ×1