简体   繁体   English

在Android中使用JSoup遇到麻烦(用于解析HTML)

[英]Having trouble with JSoup in Android (for parsing HTML)

I am working on a little test app to scrape some data (in this case, XKCD comics) from the web and display it on my phone. 我正在开发一个小型测试应用程序,以从网络上抓取一些数据(在本例中为XKCD漫画)并将其显示在手机上。 This is my first foray into Android programming and I'm not too experienced with Java so I'm not being too ambitious. 这是我第一次涉足Android编程,并且我对Java不太熟悉,因此我没有太大的野心。 I successfully wrote a program in Java that performs the same function I want to do on Android and it works wonderfully, but some of my code that works in Java causes a force close in Android. 我成功地用Java编写了一个程序,该程序执行了我想在Android上执行的功能,并且运行良好,但是我在Java中工作的某些代码在Android中导致强制关闭。 Specifically this little code block: 具体来说,这个小代码块:

try {
        home = Jsoup.connect("http://www.xkcd.com").get();
        Log.i("connect to home","completed");
    } catch (IOException e) {
        Log.i("connect to home","failed");
    }

Every time that runs, I see the "failed" message in the log. 每次运行时,我都会在日志中看到“失败”消息。 If I remove that section of my code, my app runs beautifully so I know the error must be there. 如果删除代码中的该部分,则我的应用程序可以正常运行,因此我知道错误一定存在。 "home" is defined as a Document elsewhere in my code, if you are wondering. 如果您想知道的话,“ home”在我代码的其他地方定义为Document。 In Java this runs fine, I also fond it strange that when in Eclipse developing for Android it forced me to surround that statement with a try-catch block but in Java I didn't need the try-catch. 在Java中运行良好,我也很奇怪,在为Android开发的Eclipse中,它迫使我用try-catch块包围该语句,但是在Java中,我不需要try-catch。 Any ideas why this won't work? 任何想法为什么这行不通? If you need more information, or more of my code, I will provide it (although I tried to give the full story). 如果您需要更多信息或更多代码,我将提供(尽管我尝试提供完整的故事)。

Thanks a lot for the help 非常感谢您的帮助

Every time that runs, I see the "failed" message in the log. 每次运行时,我都会在日志中看到“失败”消息。

Log the exception e . 记录异常e It contains information about how/why/where it failed. 它包含有关如何/为什么/在哪里失败的信息。 You should never suppress the exception without a very good reason (ie you know exactly what you're doing). 如果没有充分的理由(即您完全知道自己在做什么),则永远不要抑制该异常。

I also fond it strange that when in Eclipse developing for Android it forced me to surround that statement with a try-catch block but in Java I didn't need the try-catch. 我也很奇怪,在为Android开发的Eclipse中,它迫使我用try-catch块包围该语句,但是在Java中,我不需要try-catch。

Likely you already had a throws IOException on the method like so: 可能您已经在方法上throws IOException ,如下所示:

public void foo() throws IOException {
    Document document = Jsoup.connect(url).get();
    // ...
}

then you indeed don't need to put it in a try-catch. 那么您确实不需要将其放入try-catch。

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM