我想获取网页的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();
我做错了什么?
答案 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();
}
}
}