java - 安卓Java 'A resource was acquired at attached stack trace but never released'

标签 java android httpclient html

我想抓取网页的 HTML 代码,并将其显示在 edittext 控件中,但我最终遇到了这个错误:

1482-1491/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.

这是我的代码:

   class GetResult implements Runnable {
    private volatile String bodyHtml;
    @Override
    public void run() {
        try {
            String myUri = "http://www.google.com";
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(myUri);

            HttpResponse response = httpClient.execute(get);

            bodyHtml = EntityUtils.toString(response.getEntity());
            //return bodyHtml;

        } catch (IOException e) {
            bodyHtml = "kapot";
        }

    }

    public String getbodyHtml(){
        return bodyHtml;
    }


}

                String rs = "";
                GetResult foo = new GetResult();
                new Thread(foo).start();
                rs = foo.getbodyHtml();

我做错了什么?

最佳答案

您需要在 finally block 中关闭 httpClient。像这样:

public void run() {
    HttpClient httpClient = null
    try {
        String myUri = "http://www.google.com";
        httpClient = new DefaultHttpClient();
        HttpGet get = new HttpGet(myUri);

        HttpResponse response = httpClient.execute(get);

        bodyHtml = EntityUtils.toString(response.getEntity());
        //return bodyHtml;

    } catch (IOException e) {
        bodyHtml = "kapot";
    } finally {
        if (httpClient != null) { 
           httpClient.close();
        }
    }

}

关于java - 安卓Java 'A resource was acquired at attached stack trace but never released',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30427782/

相关文章:

java - 如何使用 USER 和密码从 URL 获取远程 JPG?

java - Facebook:获取 session key 时签名不正确 (104)

java - 为什么在使用 java.util.zip.ZipFile 打开一个空的 ZIP 文件时出现异常?

java - UmlGraphDoc 运行 Graphviz 时出错

android - 在 Android 上使用 Protege owl 本体

android - 为什么LiveData在Android Studio中只影响主布局而不影响子布局UI?

android - PopupWindow 中 webview 上方的按钮在 2 次后响应 onClick

java - Netty 4 HttpChunkedInput 在 HttpObjectEncoder 中抛出 "unexpected message type: DefaultHttpContent"

java - Spring 隐藏的自定义 Java 注解

java - HttpClient登录,搜索并获取XML内容