我正在通过从网站抓取HTML来开发一个Android应用程序,但是当我使用connection.get((获取文档时,我得到了NullPointerException。所以我像这样测试。
try {
conn = Jsoup.connect(url);
document = conn.get();
res = conn.execute();
} catch (IOException e) {
e.printStackTrace();
}
if (conn != null) {
textView.append("conn is not nulln");
} else {
textView.append("conn is nulln");
}
if (document != null) {
textView.append("document not is nulln");
} else {
textView.append("document is nulln");
}
if (res != null) {
textView.append("res is not null.n");
} else {
textView.append("res is nulln");
}
结果是
conn is not null.
document is null.
res is null.
我在 http://google.com 上试过这个,结果是
conn is not null.
document is not null.
res is not null.
当然,我可以得到文件。
为什么我从connection.excute((,connection.get((得到空?
首先查看文档,您不需要调用 execute 和 get: connection.get(( 方法
您没有以 GET 形式执行请求,并解析结果。
从 url 获得任何响应的原因是您尝试在主线程上运行
尝试在后台任务中运行,例如非常适合此的异步任务
private class UrlGraber extends AsyncTask<Void, Void, Void> {
private String[] urls;
@Override
protected Void doInBackground(Void... voids) {
try {
conn = Jsoup.connect(url);
document = conn.get();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
从你的onCreat((调用new urlGraber.excute()