Do I need to call HttpURLConnection.disconnect after finish using it

匿名 (未验证) 提交于 2019-12-03 00:46:02

问题:

The following code basically works as expected. However, to be paranoid, I was wondering, to avoid resource leakage,

  1. Do I need to call HttpURLConnection.disconnect, after finish its usage?
  2. Do I need to call InputStream.close?
  3. Do I need to call InputStreamReader.close?
  4. Do I need to have the following 2 line of code : httpUrlConnection.setDoInput(true) and httpUrlConnection.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);         }     } }

回答1:

Yes you need to close the inputstream first and close httpconnection next. As per 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.

Next two questions answer depends on purpose of your connection. Read this link for more details.



回答2:

I believe the requirement for calling setDoInput() or setDoOutput() is to make sure they are called before anything is written to or read from a stream on the connection. Beyond that, I'm not sure it matters when those methods are called.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!