2014-07-09 42 views
0

我正在使用crawler4j開發Grails應用程序。Crawler4j不適用於https網址

我知道這是一個古老的問題,我碰到這solution here

我試過提供的解決方案,但不知道在哪裏保留另一個fetcher和mockssl java文件。

另外,我不知道如何這兩個類將包含HTTPS URL中的情況下,被稱爲:// ...提前

感謝。

回答

0

該解決方案正常工作。也許你有一些問題需要推斷代碼的放置位置。下面是我如何使用它:

在創建爬蟲,你會在你的主類是這樣的表現在official documentation

public class Controller { 
public static void main(String[] args) throws Exception { 
    CrawlConfig config = new CrawlConfig(); 
    config.setCrawlStorageFolder(crawlStorageFolder); 

    /* 
    * Instantiate the controller for this crawl. 
    */ 
    PageFetcher pageFetcher = new MockSSLSocketFactory(config); 
    RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); 
    RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); 
    CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); 
    .... 

在這裏,您使用作爲表明被定義MockSSLSocketFactory已發佈的鏈接:

public class MockSSLSocketFactory extends PageFetcher { 

public MockSSLSocketFactory (CrawlConfig config) { 
    super(config); 

    if (config.isIncludeHttpsPages()) { 
     try { 
      httpClient.getConnectionManager().getSchemeRegistry().unregister("https"); 
      httpClient.getConnectionManager().getSchemeRegistry() 
        .register(new Scheme("https", 443, new SimpleSSLSocketFactory())); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
} 

正如你所看到的,這裏使用的是類SimpleSSLSocketFactory。這可以被定義爲在鏈路的例子顯示:

public class SimpleSSLSocketFactory extends SSLSocketFactory { 

public SimpleSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, 
     UnrecoverableKeyException { 
    super(trustStrategy, hostnameVerifier); 
} 

private static final X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() { 
    @Override 
    public void verify(String host, SSLSocket ssl) throws IOException { 
     // Do nothing 
    } 

    @Override 
    public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { 
     // Do nothing 
    } 

    @Override 
    public boolean verify(String s, SSLSession sslSession) { 
     return true; 
    } 

    @Override 
    public void verify(String arg0, java.security.cert.X509Certificate arg1) throws SSLException { 
     // TODO Auto-generated method stub 

    } 
}; 

private static final TrustStrategy trustStrategy = new TrustStrategy() { 

    @Override 
    public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { 
     return true; 
    } 
}; 

}

正如你所看到的,我只能從官方文檔,你已經發布的鏈接複製代碼,但我希望看到所有在一起會更清楚爲你。

+0

我在哪裏放這些類? –

+0

這些類必須位於您自己的項目中。控制器將是您執行應用程序時將執行的主要應用程序類。另一個類可以在你的項目的任何地方,唯一的限制是必須可以由Controller訪問。您可以像在項目中一樣複製這些類。 – JorgeHortelano