【问题标题】:Strict Mode complains on resource leak严格模式抱怨资源泄漏
【发布时间】:2012-11-28 08:05:46
【问题描述】:

严格模式抱怨以下内容:在附加的堆栈跟踪中获取了资源,但从未释放。有关避免资源泄漏的信息,请参阅 java.io.Closeable。:

**response = httpclient.execute(httpPost);**

下面是我的代码:

    HttpClient httpclient = new DefaultHttpClient();

    String url = "example";
    HttpPost httpPost = new HttpPost(url);

    HttpResponse response;
    String responseString = "";
    try {
        httpPost.setHeader("Content-Type", "application/json");

**response = httpclient.execute(httpPost);**

        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
        } else {
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    return responseString;

提前致谢。

【问题讨论】:

  • 你是否在最后一个区块中关闭了你的 HTTP 客户端。httpClient.getConnectionManager().shutdown();...

标签: java android inputstream android-strictmode bytearrayoutputstream


【解决方案1】:

从 4.3 开始,不推荐使用 kenota 指出的方法。

您现在应该使用CloseableHttpClient 而不是HttpClient,如下所示:

    CloseableHttpClient client= HttpClientBuilder.create().build();

然后您可以使用以下命令关闭它:

    client.close();

【讨论】:

  • Can't find it在文档中,有链接吗?
  • Apache Docs - 显然,Android 实际上并没有使用特定版本的 Apache HTTP (source)。我猜这意味着可以使用 kenota 提到的不推荐使用的方法(尽管我还没有实际测试过)。
  • 为什么HttpClient接口在应该可以关闭的时候却没有close方法?
  • @ADTC:来自文档:This interface represents only the most basic contract for HTTP request execution. It imposes no restrictions or particular details on the request execution process and leaves the specifics of state management, authentication and redirect handling up to individual implementations. 我猜他们只是认为它不属于那里 - 但不能说为什么。
  • 有趣的是编译器警告资源泄漏,所以当我们要修复它时,没有close()方法。然后他们不得不想出Closeable 版本来解决这个问题。 乱七八糟!
【解决方案2】:

正如 Praful Bhatanagar 指出的,您需要在 finally 块中释放资源:

HttpClient httpclient = new DefaultHttpClient();
//... code skipped
String responseString = "";
try {
//... code skipped
} catch (IOException e) {
} finally {
     httpClient.getConnectionManager().shutdown();
}

【讨论】:

  • HttpClient 类型的 getConnectionManager() 方法已弃用
猜你喜欢
  • 2019-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-10
  • 1970-01-01
  • 1970-01-01
  • 2012-12-11
  • 2020-12-09
相关资源
最近更新 更多