2009-12-22 69 views
1

我試圖執行從HTMLUnit tutorial此代碼:的Java的HtmlUnit MalformedURLException的

final WebClient webClient = new WebClient(); 
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net"); 

但在Eclipse中保存它時,我得到了MalformedURLException的第二行(如果我編譯和運行代碼,我得到它也)。有什麼問題? TIA

PS:我是新來的Java

最多:

這裏的堆棧跟蹤:

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 Source) 
    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 

回答

2

我在Eclipse 3.5嘗試這樣做,它工作正常,並測試正在通過。我假設你已經將必要的HTMLUnit JAR包含到了你的項目中?我從HTMLUnit lib目錄中取出所有JAR,並將它們添加到我的項目的構建路徑中。

此外,你可以捕捉異常並在這裏發佈堆棧跟蹤?

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(); 
} 
0
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(); 
      } 




    } 
} 
0

因爲在你的堆棧跟蹤你有

Caused by: java.lang.ClassNotFoundException: org.apache.commons.httpclient.auth.CredentialsProvider 

這是不是一個畸形URL例外。

由於confirmed by JARFinder,org.apache.commons.httpclient.auth.CredentialsProvider類應該來自commons-httpclient-3。*。jar。因此,問題的原因必須是您的類路徑中沒有Commons HTTPClient 3.x JAR。