Retrofit混淆配置
我们一般在给应用打包上线时会给代码添加混淆配置,一来是为了防止别人反编译,二来是可以给apk文件瘦身。
混淆开启方法,在应用工程下的build.gradle文件中,找到minifyEnabled配置项并设置为true,如下所示(注意这里是release配置,debug运行时混淆开关还是关着的):
android {
......
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
对于Retrofit,开启混淆开关后,我们还要在混淆文件(proguard-rules.pro)中添加一些混淆配置,在Retrofit官网中也有混淆的相关配置说明,如下所示:
如果你要在你的工程中使用混淆,需要添加以下几行配置项:
# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on RoboVM on iOS. Will not be used at runtime.
-dontnote retrofit2.Platform$IOS$MainThreadExecutor
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions
虽然官网给出了混淆配置,但还是想吐槽两句...
官网给的混淆配置其实并不完全,我们都知道Retrofit是对Okhttp的封装,Okhttp不需要添加混淆配置吗?另外,我们使用了Gson转换,Gson不需要添加混淆配置吗?还有,如果我们bean目录的数据模型的字段被混淆了,还能和服务端返回的数据对上吗?
- 第一点:如果不添加Okhttp的混淆配置,编译到okio时会报错。
- 第二点:此处Gson可以不添加混淆配置(这意味着Gson将会是混淆的)。
- 第三点:要保证我们的数据模型不被混淆,否则得到的数据全是null。
最后,给各位列一下我的混淆文件中的相关配置:
# Retrofit
-dontnote retrofit2.Platform
-dontnote retrofit2.Platform$IOS$MainThreadExecutor
-dontwarn retrofit2.Platform$Java8
-keepattributes Signature
-keepattributes Exceptions
# okhttp
-dontwarn okio.**
# Gson
-keep class com.example.testing.retrofitdemo.bean.**{*;} # 自定义数据模型的bean目录
配置之后,打包混淆后的release版应用就能拿到数据了。