The following code basically works as expected. However, to be paranoid, I was wondering, to avoid resource leakage,
- Do I need to call
HttpURLConnection.disconnect
, after finish its usage? - Do I need to call
InputStream.close
? - Do I need to call
InputStreamReader.close
? - Do I need to have the following 2 line of code :
httpUrlConnection.setDoInput(true)
andhttpUrlConnection.setDoOutput(false)
, just after the construction of httpUrlConnection?
The reason I ask so, is most of the examples I saw do not do such cleanup. http://www.exampledepot.com/egs/java.net/post.html and http://www.vogella.com/articles/AndroidNetworking/article.html. I just want to make sure those examples are correct as well.
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); } } }