我正在使用crawler4j开发一个grails应用程序。
我知道这是一个老问题,我在这里遇到了这个解决方案。
我尝试了提供的解决方案,但不确定在哪里保持另一个fetcher和mockssl java文件。
另外,我不确定在url包含https://..的情况下如何调用这两个类。
解决方案运行良好。也许你有一些问题来推断把代码放在哪里。下面是我的用法:
在创建爬虫时,您将在您的主类中拥有如下内容,如官方文档所示:
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;
}
};
}
正如你所看到的,我只是从官方文档和你发布的链接中复制代码,但我希望看到所有在一起会让你更清楚。