Android开发中如果采用的okhttp作为网络请求框架,则可以使用Chucker实现手机网络请求日志打印:

https://github.com/ChuckerTeam/chucker

但是上面的方式有局限性,所以测试经常会用到网络抓包来查看网络请求错误。 在Android6.0 及以下系统可以抓包,而 Android7.0 及以上系统不能再抓包了,因为Android7.0及以上系统版本新增了证书验证,所以 app 内不再像原来一样默认信任用户的证书了。 为了让测试能在抓包,一般都会在AndroidManifest.xml文件中配置network-security-config来实现。

允许抓包

为了让测试可抓包,配置如下:

overridePins="true"

src="system" />

overridePins="true"

src="user" />

然后在AndroidManifest.xml文件的application节点配置:

package="com.android.demo"

android:versionCode="1"

android:versionName="1.0" >

...

android:allowBackup="true"

android:label="@string/app_name"

android:networkSecurityConfig="@xml/network_security_config"

android:supportsRtl="true" >

...

为了实现抓包,测试,开发阶段可以这么配置,但是发布阶段需要禁止抓包就不能这么配置。

禁止抓包

example.com

这样配置不一样了,需要动态进行设置。

Google官方文档配置如下:

overridePins="true"

src="system" />

overridePins="true"

src="user" />

使用 debug-overrides 指定仅在 android:debuggable 为 true 时才可信的仅调试CA。 如果需要在其他条件下进行动态配置,就不能这么设置了。

第一种方式通过manifestPlaceholders,在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"

]

}

}

...

}

然后在AndroidManifest.xml文件中配置如下:

package="com.android.demo"

android:versionCode="1"

android:versionName="1.0" >

...

android:allowBackup="true"

android:label="@string/app_name"

android:networkSecurityConfig="${network_security_config}"

android:supportsRtl="true" >

...

还可以通过配置resValue来动态配置:

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文件中配置如下:

package="com.android.demo"

android:versionCode="1"

android:versionName="1.0" >

...

android:allowBackup="true"

android:label="@string/app_name"

android:networkSecurityConfig="@xml/network_security_config"

android:supportsRtl="true" >

...

这样就能实现动态配置了,非常方便。

感谢大家的支持,如有错误请指正,如需转载请标明原文出处!

相关文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。