Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/202.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 严格模式抱怨资源泄漏_Java_Android_Inputstream_Android Strictmode_Bytearrayoutputstream - Fatal编程技术网

Java 严格模式抱怨资源泄漏

Java 严格模式抱怨资源泄漏,java,android,inputstream,android-strictmode,bytearrayoutputstream,Java,Android,Inputstream,Android Strictmode,Bytearrayoutputstream,严格模式抱怨如下:在附加的堆栈跟踪中获取了资源,但从未释放。有关避免资源泄漏的信息,请参见java.io.Closeable.: **response = httpclient.execute(httpPost);** 下面是我的代码: HttpClient httpclient = new DefaultHttpClient(); String url = "example"; HttpPost httpPost = new HttpPost(url);

严格模式抱怨如下:在附加的堆栈跟踪中获取了资源,但从未释放。有关避免资源泄漏的信息,请参见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;

提前感谢。

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


截至4.3,kenota指出的方法已被弃用

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

    CloseableHttpClient client= HttpClientBuilder.create().build();
然后,您可以使用以下方法将其关闭:

    client.close();

是否在最后一个块中关闭HTTP客户端<代码>httpClient.getConnectionManager().shutdown()在文档中,是否有链接?-显然,Android实际上并没有使用Apache HTTP()的特定发布版本。我想这意味着可以使用kenota提到的不推荐的方法(虽然我还没有实际测试过)。为什么
HttpClient
接口在应该可以关闭时没有
close
方法?@ADTC:来自文档:
此接口仅代表HTTP请求执行的最基本契约。它没有对请求执行过程施加任何限制或特定细节,并将状态管理、身份验证和重定向处理的细节留给各个实现。
我猜他们只是认为它不属于那里,但无法说明原因。有趣的是,编译器警告资源泄漏,因此,当我们想要修复它时,没有
close()
方法。然后,他们必须拿出
可关闭的
版本来解决这个问题。凌乱的HttpClient类型的getConnectionManager()方法已被弃用
    client.close();