android - 使用完毕后是否需要调用 HttpURLConnection.disconnect

标签 android

以下代码基本上可以按预期工作。然而,偏执,我想,为了避免资源泄漏,

  1. HttpURLConnection.disconnect用完后需要调用吗?
  2. 我需要调用 InputStream.close 吗?
  3. 我需要调用 InputStreamReader.close 吗?
  4. 在构建httpUrlConnection之后是否需要有以下两行代码:httpUrlConnection.setDoInput(true)httpUrlConnection.setDoOutput(false)

我之所以这么问,是因为我看到的大多数示例都没有进行此类清理。 http://www.exampledepot.com/egs/java.net/post.htmlhttp://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/

相关文章:

android - 解决按钮中多次单击的更优雅的方法

android - 后台模式总是从 INDEX 重新启动后,Android 5.1 上的 CORDOVA/PHONEGAP

android - 如何在android中获取目录设备中的文件?

java - 带有 NavigationDrawer 的 fragment 中的 TabHost

android - 在项目结构中找不到导入模块选项(Android Studio 0.3.4 - 0.5.2)

android - 如何在多个应用程序通用的库中包含的方法中获取应用程序的 VERSION_NAME?

android - 我的 Recyclerview 在 NestedScrollview 里面,它正在工作,但滚动不流畅

android - 如何处理包含带括号的字符串的 JSON?

java - RecyclerView onClickItem 没有响应点击

android - 在 Android 上检测重要的设备运动