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