Android Studio 如何仅在调试模式下将cleartextTrafficPermitted设置为true?

xdyibdwo  于 2023-02-05  发布在  Android
关注(0)|答案(2)|浏览(134)

目前我有以下网络安全配置xml文件:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <!-- default config that does not allow clear test -->
    <base-config cleartextTrafficPermitted="false">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
    
  <!-- trying to get debug override to change this -->
    <debug-overrides cleartextTrafficPermitted="true (DOESN'T WORK)">
        <trust-anchors>
            <certificates src="system" />
            <certificates src="user" />
        </trust-anchors>
    </debug-overrides>
</network-security-config>

我所要做的只是在开发/调试模式下有条件地启用全局域清除流量。
当我发现标签<debug-overrides>...</debug-overrides>时,我以为我已经找到了答案,但它没有起作用。
不幸的是,根据官方文档,该标记实际上并不支持所需的属性。

41zrol4v

41zrol4v1#

没关系,我已经知道如何使用gradle运行时变量来实现它了。

// In your app level gradle file `build.gradle`

android
{
    ...
    
    buildTypes
    {
        debug
        {
            resValue "string", "clear_text_config", "true"
        }
        release
        {
            resValue "string", "clear_text_config", "false"
        }
    }

    ...
}

// In your network security configuration xml

<base-config cleartextTrafficPermitted="@string/clear_text_config">
    <trust-anchors>
      <certificates src="system" />
    </trust-anchors>
</base-config>

这是因为gradle会自动为您生成资源文件。

nimxete2

nimxete22#

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config>
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
    <debug-overrides>
        <trust-anchors>
            <certificates src="user" />
        </trust-anchors>
    </debug-overrides>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">xxx.xxx.xxx</domain>
    </domain-config>
</network-security-config>

使用域配置是更好的方法。我们通常不在正式环境中使用http。

相关问题