严格模式抱怨资源泄漏

mun*_*ikh 4 java android inputstream bytearrayoutputstream android-strictmode

严格模式会引发以下情况:在附加的堆栈跟踪中获取资源但从未释放.有关避免资源泄漏的信息,请参阅java.io.Closeable:

**response = httpclient.execute(httpPost);**
Run Code Online (Sandbox Code Playgroud)

以下是我的代码:

    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;
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Tsp*_*oon 6

从4.3开始,kenota指出的方法已被弃用.

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

    CloseableHttpClient client= HttpClientBuilder.create().build();
Run Code Online (Sandbox Code Playgroud)

然后你可以用以下方法关闭它:

    client.close();
Run Code Online (Sandbox Code Playgroud)

  • [Apache Docs](http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/CloseableHttpClient.html) - 显然Android实际上并没有使用特定版本Apache HTTP的版本([来源](http://stackoverflow.com/questions/2618573/what-version-of-apache-http-client-is-bundled-in-android-1-6)).我猜这意味着可以使用kenota提到的弃用方法(虽然我实际上没有测试过这个). (2认同)
  • 有趣的是,编译器会警告资源泄漏,因此,当我们要修复它时,没有`close()`方法。然后他们不得不想出`Closeable`版本来解决这个问题。**凌乱!** (2认同)