Android Java'资源是在附加的堆栈跟踪中获得的,但从未发布过#&

时间:2015-05-24 20:03:24

标签: java android httpclient webpage

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

  

1482-1491 / android.process.acore E / StrictMode:获取了一个资源   附加堆栈跟踪但从未发布。请参阅java.io.Closeable   有关避免资源泄漏的信息。

这是我的代码:

   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();

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您需要在finally块中关闭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();
        }
    }

}