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

生成Android Baseline Profile时Ktor网络请求崩溃问题求助

解决Baseline Profile生成时Ktor网络请求的CertificateException异常

生成Baseline Profile时,Android编译/测试环境的SSL证书验证逻辑和正常启动场景存在差异,Ktor默认配置未触发域名校验的checkServerTrusted方法,从而抛出证书异常。以下是针对性解决方案:

1. 显式配置Ktor的SSL主机名验证

在Ktor HttpClient配置中强制启用主机名验证,确保使用支持域名校验的逻辑。示例代码:

val client = HttpClient(Android) {
    // 保留原有ContentNegotiation、超时等配置
    install(ContentNegotiation) {
        json()
    }
    install(HttpTimeout) {
        requestTimeoutMillis = 10000
    }

    // 添加SSL主机名验证配置
    engine {
        hostnameVerifier = HostnameVerifier { hostname, session ->
            // 复用系统默认的主机名验证逻辑
            HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)
        }
        configureSsl { sslContext ->
            // 确保启用合规的TLS协议版本
            sslContext.serverSocketFactory.createSocket().use { socket ->
                (socket as SSLSocket).enabledProtocols = arrayOf("TLSv1.2", "TLSv1.3")
            }
        }
    }
}

2. 临时添加网络安全配置(仅用于Profile生成)

若不想修改Ktor代码,可临时添加网络安全配置放宽SSL验证,完成Profile生成后再移除:

  1. 在src/main/res/xml目录创建network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config>
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
    <domain-config includeSubdomains="true">
        <domain>你的API域名</domain>
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </domain-config>
</network-security-config>
  1. 在AndroidManifest.xml的<application>标签中引用该配置:
<application
    ...
    android:networkSecurityConfig="@xml/network_security_config">
    ...
</application>

3. 检查Profile生成环境的基础配置

  • 确认生成Profile使用的设备/模拟器系统时间正确,避免因时间偏差导致证书过期校验失败;
  • 确保API域名的SSL证书由公共可信CA颁发,若使用自签名证书,需将证书添加到设备信任列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:08:31