I've encountered a very weird bug in my code. On android 2.3, the following code runs just fine - never seeing the exception in logcat. However, on 2.2, the exception always happens - but manages to connect on the second try.
try {
currentTempDocument = Jsoup.connect(url).cookie("vbscansessionhash", LoginManager.getSessionValue()).get();
} catch(IOException e) {
Log.i(TAG, "Exception!", e);
try {
currentTempDocument = Jsoup.connect(url).cookie("vbscansessionhash", LoginManager.getSessionValue()).get();
} catch(IOException e2) {
}
}
The exception I'm getting is:
java.io.IOException: -1 error loading URL https://www.flashback.org/f4
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:387)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:396)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:364)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:143)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:132)
at org.chip2n.flashback.HtmlReader.loadTempDocument(HtmlReader.java:69)
at org.chip2n.flashback.Browser$7.run(Browser.java:295)
The same exact error seem to occur if I switch https to http in the url (it still shows开发者_高级运维 https://... in the exception though, which it shouldn't (?)). Also, when I clean my eclipse project, the above code works without the exception - but only the first time the code runs.
Oh, and the exception happens immediately - it's like there's no internet connection at all.
What am I missing here?
It seems JSoup is trying to read cookies from a previous HttpConnection
On first try, no old connection, so the code works fine, but on second try, it may be trying to read cookies from the past connection, which is closed, or dereferenced.
I did not go as far as reading the Android 2.2 code, but probably the best way for you is to continue doing things the way you are doing right now.
Since it works fine on 2.3, as it should, I am tempted to say it's a mismatch between the way Android 2.2 handles cookies, and the way JSoup handles HttpConnection.
This problem occurs not only using cookies, but also doing two simple connections using currentTempDocument = Jsoup.connect(url).get(); to read 2 different urls in the same activity: when I attempt to read the second url, only the 2nd attempt is ok. This problem disappears as suggested in the comment, i.e using
System.setProperty("http.keepAlive", "false");
or also as suggested in the question, i.e. using two nested try/catch blocks so that when the 1st attempt fails, the 2nd one goes ok
精彩评论