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

Android应用本地测试HTTPS问题:自签名证书主机名验证失败

Android自签名证书主机名验证失败问题

问题描述

本地测试Android应用,需从192.168.1.16获取数据,服务器使用自签名证书,已完成以下配置:

  • 将证书存储在res/raw/laragon_certif
  • 创建res/xml/network_security_config.xml文件,指向@raw/laragon_certif
  • 在AndroidManifest.xml的<application>节点添加android:networkSecurityConfig="@xml/network_security_config"属性

当前出现异常:

javax.net.ssl.SSLPeerUnverifiedException: Hostname 192.168.1.16 not verified:
certificate: sha1/Gr8h0ea/mhIMIADb7CMK47K8Moo=
DN: CN=laragon,OU=IT,O=Laragon,L=Singapore,ST=Singapore,C=SG
subjectAltNames: [localhost, ..., ..., ..., 192.168.1.16]

应用已识别自签名证书但不认为其覆盖192.168.1.16主机名。

解决方案

1. 检查证书的SAN条目类型

用openssl工具查看证书详情,确认Subject Alternative Name中192.168.1.16是IP地址类型而非DNS类型:

openssl x509 -in laragon_certif -text -noout

正确的条目格式应为:

Subject Alternative Name:
    DNS:localhost, IP Address:192.168.1.16

如果显示为DNS:192.168.1.16,需重新生成证书,添加IP类型的SAN条目。

2. 调整Network Security Config

修改res/xml/network_security_config.xml,为目标IP添加明确的域配置:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config>
        <domain includeSubdomains="false">192.168.1.16</domain>
        <trust-anchors>
            <certificates src="@raw/laragon_certif"/>
        </trust-anchors>
    </domain-config>
</network-security-config>

3. 临时方案:自定义HostnameVerifier(仅用于测试)

如果使用OkHttp发起请求,可临时添加自定义主机名验证逻辑(不建议生产环境使用):

OkHttpClient client = new OkHttpClient.Builder()
    .hostnameVerifier((hostname, sslSession) -> {
        return hostname.equals("192.168.1.16");
    })
    .build();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:13:11