gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:08:26 27 4
gpt4 key购买 nike

我想抓取网页的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com