java - Android 使用 Jsoup 解析 HTML 时出现问题

标签 java html parsing android-studio jsoup

我们在 android studio 中使用 jsoup 解析实时 url 时遇到问题。相同的代码将在 eclipse 中工作。我们收到错误

Method threw 'java.lang.NullPointerException' exception.can not evaluate org.jsoup.parser.HtmlTreebuilder.tostring()

这是我的 Activity 代码

String title=null;
    Document document;
    try {
        document= Jsoup.connect("https://www.facebook.com/")
                .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                .referrer("http://www.google.com")
                .get();
        title=document.title();
        TextView text=(TextView)findViewById(R.id.textView);
        text.setText(title);

    } catch (Exception e) {
        e.printStackTrace();
        Log.d("tag","document");

    }

如何解决此问题并从实时网址获取标题?

最佳答案

您可以使用AsyncTask类来避免NetworkOnMainThreadException 您可以在这里尝试此代码。

private class FetchWebsiteData extends AsyncTask<Void, Void, Void> {
    String websiteTitle, websiteDescription;

    @Override
    protected void onPreExecute() {
        //progress dialog
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            // Connect to website
            Document document = Jsoup.connect(URL).get();
            // Get the html document title
            websiteTitle = document.title();
            Elements description = document.select("meta[name=description]");
            // Locate the content attribute
            websiteDescription = description.attr("content");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // Set title into TextView
        TextView txttitle = (TextView) findViewById(R.id.txtData);
        txttitle.setText(websiteTitle + "\n" + websiteDescription);
        mProgressDialog.dismiss();
    }
}

}

并添加您的 mainActivity

new FetchWebsiteData().execute();

关于java - Android 使用 Jsoup 解析 HTML 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29405761/

相关文章:

javascript - 动态创建 DIV 后超链接不起作用

javascript - 吉他和弦自定义标签简单解析器

java - 使用 java 映射一些名称和值

java - 如何使用带有 Maven 覆盖层的嵌入式 Jetty

java 二维数组二次​​排序

excel - VB .NET 中的 CDbl 和小数分隔符 - 有没有办法绕过区域设置?

sql - 去除单词中的空格

java - 如何在 Spring Boot 中从 Java 设置 TCPConnectionFactory 或 SSLServerSocketFactory

javascript - ng-src 中的函数执行多次

jquery - 如何对 iframe 子元素应用 3D 变换?