我试图在Android中使用HttpClient()
抓取网页的HTML代码。 getbodyHtml
返回空,而在输出中,我看到HTML代码打印正常。我做错了什么?
class GetResult implements Runnable {
public volatile String bodyHtml;
public volatile boolean finished = false;
@Override
public void run() {
finished = false;
HttpClient httpClient = new DefaultHttpClient();
try {
String myUri = "http://google.com";
HttpGet get = new HttpGet(myUri);
HttpResponse response = httpClient.execute(get);
bodyHtml = EntityUtils.toString(response.getEntity());
//return bodyHtml;
finished = true;
System.out.println(bodyHtml);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public String getbodyHtml(){
return bodyHtml;
}
}
而且:
String rs = "";
GetResult foo = new GetResult();
new Thread(foo).start();
if (foo.finished = true){
rs = foo.getbodyHtml();
}
edittext2.setText(rs);
答案 0 :(得分:0)
因为检查时Foo没有完成,所以不要输入if。要更正此调用foo.join(),请执行以下操作:
String rs = "";
GetResult foo = new GetResult();
new Thread(foo).start();
foo.join(); // will wait till foo finish
rs = foo.getbodyHtml();
edittext2.setText(rs);