gpt4 book ai didi

android - 如何避免强制关闭 IOException 和 SocketTimeoutException JSoup?

转载 作者:行者123 更新时间:2023-11-29 16:21:25 26 4
gpt4 key购买 nike

我正在使用这段代码来检索 html 页面并解析它

while(doc == null && retry<5){
retry++;
try {
doc = Jsoup.connect(url).get();
} catch (IOException e) {
Log.e("ReleaseInfo", "JSoup get didnt get a document", e);


}

检索到文档后,我将使用它来获取一些信息并测试是否为空。

  overview = doc.select("div#object-overview").last();


if(overview != null){

paragraph = overview.select("p").last();

if(paragraph != null){
Log.v("Paragraph", paragraph.text());

}else{

Toast.makeText(releaseInfo.this, "No over view content", Toast.LENGTH_SHORT);
}


}

else{


}

featureList = doc.select("div.callout-box").last();


if(featureList != null){
Log.v("OverView", featureList.text());

如您所见,我正在使用日志语句捕获错误。 IOException 告诉我这个

08-17 12:54:11.535: ERROR/ReleaseInfo(5960): JSoup get didnt get a document
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): java.net.SocketTimeoutException
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): at org.apache.harmony.luni.net.PlainSocketImpl.read(PlainSocketImpl.java:564)
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): at org.apache.harmony.luni.net.SocketInputStream.read(SocketInputStream.java:88)
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): at java.io.InputStream.skip(InputStream.java:258)
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): at org.apache.harmony.luni.net.SocketInputStream.skip(SocketInputStream.java:93)
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl$ChunkedInputStream.skipOutstandingChunks(HttpURLConnectionImpl.java:374)

我如何让我的代码防御此错误,以便在未检索文档时不强行关闭?

我还想捕获并响应导致我的应用程序强制关闭的异常。

08-17 16:27:29.245: ERROR/ReleaseInfo(8641): JSoup get didnt get a document
08-17 16:27:29.245: ERROR/ReleaseInfo(8641): java.io.IOException: 404 error loading URL http://pc.gamespy.com/web-games/parking-wars-2/
08-17 16:27:29.245: ERROR/ReleaseInfo(8641): at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:387)
08-17 16:27:29.245: ERROR/ReleaseInfo(8641): at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:364)
08-17 16:27:29.245: ERROR/ReleaseInfo(8641): at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:143)
08-17 16:27:29.245: ERROR/ReleaseInfo(8641): at org.jsoup.helper.HttpConnection.get(HttpConnection.java:132)

最佳答案

您显示的日志条目表明您捕获了异常并将其作为错误打印到日志中,正如您所期望的那样。这些条目都不应强制关闭您的应用程序。还有其他条目吗?例如,如果在你重试 5 次之后你仍然没有建立连接,那么 'doc' 将等于 null 并且以下行将导致未捕获的 nullPointerException 然后将关闭你的应用程序:

overview = doc.select("div#object-overview").last();

关于android - 如何避免强制关闭 IOException 和 SocketTimeoutException JSoup?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7099284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com