【问题标题】:Retrofit 2.4.0 with proguard使用 proguard 改造 2.4.0
【发布时间】:2018-06-05 18:41:56
【问题描述】:

当我将 Retrofit 2.4.0 库添加到 android 项目时 >

implementation 'com.squareup.retrofit2:retrofit:2.4.0'

并设置 minifyEnabled {true}

 buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

然后将这些规则添加到 proguard-rules.pro

-keep class com.squareup.** { *; }
-keep interface com.squareup.** { *; }
-keep class retrofit2.** { *; }
-keep interface retrofit2.** { *;}
-keep interface com.squareup.** { *; }


-keepclasseswithmembers class * {
    @retrofit2.http.* <methods>;
}


-dontwarn rx.**
-dontwarn retrofit2.**
-dontwarn okhttp3.**
-dontwarn okio.**

最终成功构建并生成签名 apk,但问题是运行(发布 apk)> 改造请求未发送并返回 { null } .. 请问有什么解决办法!

【问题讨论】:

    标签: java android retrofit2


    【解决方案1】:

    可能是因为其他库与您的下载器或解析器等进行了改造。

    重要提示:

    添加规则以保持您的模型类和主题与解析器一起使用,例如:

    -keep class com.address_package.** { *; }
    

    如果你使用 okhttp 或 Okhttp3 并在规则下方添加了改造

    注意:并检查您的解析器保护规则

    库:OkHttp

    -keep class com.squareup.okhttp.** { *; }
    -keep interface com.squareup.okhttp.** { *; }
    
    -dontwarn com.squareup.okhttp.**
    -dontwarn okio.**
    

    okhttp3

    -keepattributes Signature
    -keepattributes *Annotation*
    -keep class okhttp3.** { *; }
    -keep interface okhttp3.** { *; }
    
    -dontwarn okhttp3.**
    

    【讨论】:

    • 找到了 protobuf 消息,但 k.a.b.q 没有 parser() 方法或 PARSER 字段。我在 proguard-android.txt 中包含了 proto 类
    • @LeresAldtai 也许这个sample可以帮助你
    • 为什么要保持okhttp?
    • @c-an 如果作为客户端使用,需要保留,否则不需要
    【解决方案2】:

    您的 Proguard 规则适用于 Retrofit,但它们也会混淆您用于序列化/反序列化数据的模型类。它们的名字很重要,因为 Retrofit/Gson 匹配它们来进行序列化/反序列化。 Proguard 将它们变成像 ab 这样的乱码,因此 Retrofit/Gson 无法理解它们。

    根据您的软件包设置,您需要像提到的 amin mahmodi 一样添加以下内容。

    -keep class your.package.name.models.** { *; }

    【讨论】:

      【解决方案3】:

      这个答案可能很晚,但它可以帮助其他人。

      而不是保留整个类:

      -keep class your.package.name.models.** { *; }
      

      你可以使用:

      -keepclassmembers class * {
         @com.google.gson.annotations.SerializedName <fields>;
      }
      

      这将允许您将模型放置在您想要的任何位置,并且不会在每次更改项目位置时将它们作为单独的规则包含在 ProGuard 文件中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-27
        • 2017-04-29
        • 2015-12-25
        • 2018-12-09
        • 2018-11-13
        相关资源
        最近更新 更多