Rem*_*_rm 0 https android http android-manifest android-network-security-config
从 Android 9 开始,Android 默认情况下仅允许通过 HTTPS 进行网络连接。然而,我正在做的唯一请求是通过本地主机(例如http://10.41.199.226:port/FooBar)完成的,该本地主机由HttpListener侦听该地址:端口组合的(C#)处理。
由于此请求是通过 HTTP 发出的,因此 Android 默认情况下不允许这样做。按照Android 关于该文件的文档,network_security_config我可以通过添加以下network_security_config.xml文件来允许 HTTP 连接
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
<certificates src="user" />
</trust-anchors>
</base-config>
<debug-overrides>
<trust-anchors>
<certificates src="user" />
</trust-anchors>
</debug-overrides>
</network-security-config>
Run Code Online (Sandbox Code Playgroud)
这是使用 Android 清单调用的android:networkSecurityConfig="@xml/network_security_config"。
这允许完成 HTTP 请求,但是因为这设置了基本配置,所以允许在整个应用程序中发出 HTTP 请求。这不是一个好主意,因为我将来可能想添加传出请求,我希望通过 HTTPS 发送请求,并且希望为此建立安全网。让这成为一条不可行的道路。
在同一文档中,他们进一步介绍了domain-config允许您根据域进行设置的功能cleartextTrafficPermitted,我尝试使用以下域集进行设置
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">127.0.0.1</domain>
<domain includeSubdomains="true">10.0.0.1</domain>
<domain includeSubdomains="true">localhost</domain>
</domain-config>
</network-security-config>
Run Code Online (Sandbox Code Playgroud)
由于没有结果,请求仍然因不是 https 而被阻止。
我查找了设备的本地地址,并将其添加到域列表中
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">10.41.199.226</domain> <!--assume this is my local ip -->
</domain-config>
Run Code Online (Sandbox Code Playgroud)
这很有效,并且仅当通过本地主机请求时才允许使用 HTTP,而任何传出请求都需要 HTTPS。
唯一的问题是我无法在应用程序启动之前知道运行该应用程序的设备的本地 IP。
所以我的问题是,有没有办法:
localhost我尝试过的那样,但没有成功)includeSubdomains="true"在添加地址时能够为我执行此操作10.0.0.0。但事实并非如此)network_security_config.xml在运行时编辑文件,以便在启动应用程序时将其中一个域条目的域名动态更新为当前本地 IP?该应用程序是使用 Unity 2019.1.8 使用 .net 4.x IL2CPP 脚本运行时开发的
实现这一点的简单方法是将此属性用于您的 AndroidManifest.xml,您可以在其中允许所有请求的所有 http:
android:usesCleartextTraffic="true"
Run Code Online (Sandbox Code Playgroud)
但是,如果您想要为不同的链接进行更多配置,例如允许某些域使用 http 而不允许其他域,则您必须提供networkSecurityConfig文件。
要在 Android 9 Pie 中执行此操作,您必须像这样networkSecurityConfig在 Manifestapplication标签中设置一个:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:networkSecurityConfig="@xml/network_security_config">
</application>
</manifest>
Run Code Online (Sandbox Code Playgroud)
然后在您的 xml 文件夹中,您现在必须创建一个名为 network_security_config 的文件,就像您在清单中命名它的方式一样,从那里您的文件内容应该是这样的,以启用所有不加密的请求:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
Run Code Online (Sandbox Code Playgroud)
从那里你很高兴去。现在您的应用程序将对所有类型的连接发出请求。有关此主题的更多信息https://developer.android.com/training/articles/security-config。