I'm trying to execute this code from the HTMLUnit tutorial:
final WebClient webClient = new WebClient();
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
but I get the MalformedURLException in the second line when saving it in Eclipse (if I compile and run the code, I get it too). What's the problem? TIA
PS: I'm new to Java
Up:
Here's the stack trace:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/httpclient/auth/CredentialsProvider
at Tester.main(Tester.java:12)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.httpclient.auth.CredentialsProvider
at java.net.URLClassLoader$1.run(Unknown So开发者_如何学Pythonurce)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 1 more
I tried this in Eclipse 3.5 and it is working correctly, and the test is passing. I assume that you have included the necessary HTMLUnit JARs into your project? I took all the JARs from the HTMLUnit lib
directory and added them to the build path of my project.
Also, can you catch the exception and post the stack trace here?
try {
final WebClient webClient = new WebClient();
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
}
catch (Exception e) {
e.printStackTrace();
}
package com.project.test;
import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class Practice1 {
public static void main(String[] args) {
final WebClient webClient = new WebClient();
HtmlPage page;
try {
page = (HtmlPage) webClient.getPage("http://htmlunit.sourceforge.net");
System.out.println("Title="+ page.getTitleText());
} catch (FailingHttpStatusCodeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Since in your stacktrace you have
Caused by: java.lang.ClassNotFoundException: org.apache.commons.httpclient.auth.CredentialsProvider
this isn't a malformed URL exception.
As confirmed by JARFinder, org.apache.commons.httpclient.auth.CredentialsProvider class should come from commons-httpclient-3.*.jar. Thus the cause of the problem must be that you don't have Commons HTTPClient 3.x JARs in your classpath.
精彩评论