相关疑难解决方法(0)

完成使用后我是否需要调用HttpURLConnection.disconnect

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

  1. HttpURLConnection.disconnect完成使用后我需要打电话吗?
  2. 我需要打电话InputStream.close吗?
  3. 我需要打电话InputStreamReader.close吗?
  4. 我是否需要具有以下2行代码:httpUrlConnection.setDoInput(true)并且httpUrlConnection.setDoOutput(false),在构建httpUrlConnection之后?

我这么说的原因是,我看到的大部分例子都没有做过这样的清理.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) …
Run Code Online (Sandbox Code Playgroud)

android

26
推荐指数
1
解决办法
2万
查看次数

标签 统计

android ×1