You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按博客步骤用HtmlUnit爬取网页时遇HttpClientBuilder.dnsResolver字段找不到错误

问题描述

我按照某博客步骤使用Java + HtmlUnit进行网页爬取,执行代码:

HtmlPage myPage = webClient.getPage("https://devpal.co");

时触发错误:

java.lang.IllegalArgumentException: Cannot locate declared field class org.apache.http.impl.client.HttpClientBuilder.dnsResolver

我的pom.xml中HtmlUnit依赖配置如下(完整pom配置可查看gist):

<dependency>
    <groupId>net.sourceforge.htmlunit</groupId>
    <artifactId>htmlunit</artifactId>
    <version>2.70.0</version>
</dependency>
原因分析

这个错误源于Apache HttpClient版本冲突:HtmlUnit 2.70.0依赖特定版本的HttpClient(4.5.14及兼容版本),若项目中其他依赖引入了不兼容的HttpClient版本(过高或过低),会导致类结构不匹配,进而找不到dnsResolver字段。

解决方案

1. 强制统一HttpClient版本

在pom.xml中直接添加HttpClient依赖,指定与HtmlUnit 2.70.0兼容的版本:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version>
</dependency>

2. 升级HtmlUnit至最新稳定版

HtmlUnit后续版本已优化依赖兼容性,升级到2.71.0及以上版本可解决该问题:

<dependency>
    <groupId>net.sourceforge.htmlunit</groupId>
    <artifactId>htmlunit</artifactId>
    <version>2.71.0</version>
</dependency>

3. 排查并排除冲突依赖

执行Maven命令查看依赖树,定位冲突的HttpClient来源:

mvn dependency:tree

找到引入冲突版本的依赖后,添加排除规则:

<dependency>
    <!-- 替换为实际引入冲突的依赖坐标 -->
    <groupId>xxx</groupId>
    <artifactId>xxx</artifactId>
    <version>xxx</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </exclusion>
    </exclusions>
</dependency>

内容的提问来源于stack exchange,提问作者vikramvi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 03:24:59