ClassCastException in web client

I use the web client to get the page source. The first time I get the page source. After I use the same object to get the page source for a different URL, it shows an exception like:

java.lang.ClassCastException: com.gargoylesoftware.htmlunit.UnexpectedPage cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlPage 

This is the code I'm using.

 HtmlPage firstPage = webClient.getPage("firsturl"); HtmlPage downloadPage = null; try { webClient.setJavaScriptEnabled(true); downloadPage = (HtmlPage) webClient.getPage("secondurl"); } catch (Exception e) { e.printStackTrace(); } 

thanks in advance

+4
source share
2 answers

That said clearly, your code does:

 downloadPage = (HtmlPage) webClient.getPage("secondurl"); 

so you assume that you are getting an object of type HtmlPage , but in fact you are getting an object of type UnexpectedPage .

You should add an instanceof check:

 If (webClient.getPage("secondurl") instanceof HtmlPage){ downloadPage = (HtmlPage) webClient.getPage("secondurl"); } else{ //do something } 
+1
source

I assume (without knowing the library too well) that UnexpectedPage is a subtype of HtmlPage (if not, the cause of your problem).

In this case, you probably have these classes twice in the class path. Although the "name" of the HtmlPage class looks like a legitimate superclass, the class loader has access to two classes with the same name and the "other" is loaded first.

Check (double check) the HtmlUnit classes that appear twice in your class path.

+1
source

All Articles