我正在通过从网站抓取HTML开发一个Android应用程序,但是当我使用connection.get()来获取Document时,我得到了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 null\n");
} else {
textView.append("conn is null\n");
}
if (document != null) {
textView.append("document not is null\n");
} else {
textView.append("document is null\n");
}
if (res != null) {
textView.append("res is not null.\n");
} else {
textView.append("res is null\n");
}
,结果是
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.
当然,我可以获得Document。
为什么我从connection.excute(),connection.get()?
获取null答案 0 :(得分:0)
首先查看文档,您不需要调用execute和get:connection.get()方法
以GET身份执行请求,并解析结果。
您之所以没有从您的网址获得任何回复,是因为它会引发异常。看一下文档:https://jsoup.org/apidocs/ 要了解您的错误原因,只需记录异常并查看日志
答案 1 :(得分:0)
尝试在后台任务中运行,例如asynctask完美适用于此
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()