Android动态配置network
•
移动开发
相信目前Android开发中,基本上网络请求都是使用https协议的了,这样对我们的数据安全有了一定的保障。但是通常在测试阶段,测试人员往往需要进行抓包测试,可以实时查看数据请求情况。这就需要我们需要区分好生产环境和测试环境的网络安全配置了。这时就需要我们用到network_security_config的文件配置了。
下面有三种方法实现这个需求:
第一种: debug-overrides
通过debug-overrides来实现debug打包时,信任用户的证书,即可以实现代理抓包。
第二种:利用 manifestPlaceholders
这个方法类似于打渠道包的原理,通过gradle来动态配置不同的network_security_config文件。
1、创建network_security_config_debug,network_security_config_release
network_security_config_debug :
network_security_config_release :
2、
在app模块的build.gradle文件中添加以下代码:
android {
...
buildTypes {
debug {
...
manifestPlaceholders = [
network_security_config: "@xml/network_security_config_debug"
]
}
release {
...
manifestPlaceholders = [
network_security_config: "@xml/network_security_config_release"
]
}
}
}
3、
在AndroidManifest.xml文件中添加以下代码:
...
这样就可以动态配置network_security_config了。
第三种:resValue
其实这种方法,和第二种是异曲同工的方法,都是利用gradle进行动态编译配置,只不过写法不一样罢了。
首先都是需要和第二步那样创建network_security_config_debug,network_security_config_release两个文件。
然后在app模块的build.gradle文件中添加以下代码:
android {
...
buildTypes {
debug {
...
resValue "xml", "network_security_config", "@xml/network_security_config_debug"
}
release {
...
resValue "xml", "network_security_config", "@xml/network_security_config_release"
}
}
}
然后在AndroidManifest.xml文件中添加以下代码:
...
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/209c571d3e.html
