【问题标题】:body params properties name change in signed APK签名 APK 中的正文参数属性名称更改
【发布时间】:2021-10-05 10:13:39
【问题描述】:

我创建了一个 android 应用程序,我使用改造作为 REST 客户端。

当我在手机上安装应用程序时,发送请求没有任何问题,但是当我构建签名的 APK 时,我不知道为什么发送请求时属性名称会更改

我有一个包含“电话”字段的类,那么请求正文必须是

{
    "phone": "123456"
}

但在日志中,我看到身体变成了

{
    "a": "123456"
}

问题仅出现在签名的 APK 中,

有什么帮助吗?

【问题讨论】:

    标签: android retrofit retrofit2


    【解决方案1】:

    快速修复禁用 minifyEnabled 为 false。

    release {
            minifyEnabled false
            ...
        }
    

    如果您不希望您的班级成员被混淆,请使用 Gson 提供的 SerializedName 注释。例如:

    public class ClassNameHere
    {
       @SerializedName("phone")
       public String phone;
         ...
    
    }
    

    此外,请确保您也为 Gson 库添加了正确的 proguard 配置。例如:

    ##---------------Begin: proguard configuration for Gson ----------
    # Gson uses generic type information stored in a class file when working with
    #fields. Proguard removes such information by default, so configure it to keep
    #all of it.
    -keepattributes Signature
    -keep class com.mypackage.ClassNameHere.** { *; }
    -keep class com.google.gson.examples.android.model.** { *; }
    # For using GSON @Expose annotation
    -keepattributes *Annotation*
    
    # Gson specific classes
    -keep class sun.misc.Unsafe { *; }
    #-keep class com.google.gson.stream.** { *; }
    
    # Application classes that will be serialized/deserialized over Gson
    -keep class com.google.gson.examples.android.model.** { *; }
    
    ##---------------End: proguard configuration for Gson ----------
    

    有关更多信息,请阅读 proguard 规则

    【讨论】:

    • 感谢您的回答 :) 我必须对所有属性使用注释吗?我还有其他方法可以使用吗?因为我有很多关于身体参数的查询
    • @Ghaylen 我刚刚更新了快速修复的答案,请检查
    • 很高兴为您提供帮助?
    【解决方案2】:

    看起来像 R8 / proguard 问题。

    对于调试版本,它通常被禁用,因此不会进行优化和混淆,但对于发布 apk,它通常是打开的(应该如此!)。

    // this line in build.gradle
    minifyEnabled true
    

    这不取决于改造,而是您的 json 转换器、GSON 或 Moshi 或其他任何东西。您需要“保留”(通过调整 proguard 规则)您的模型类或正确注释它们,以便转换器按预期工作。

    对于moshi,通常的方式是通过注解处理器生成模型的json转换器

    @JsonClass(generateAdapter = true) 
    class PhoneModel(@Json(name = "phone") val phoneField: String)
    

    但是请在 proguard / R8 上查看转换器的自述页面

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 2012-01-18
      • 2017-06-24
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      相关资源
      最近更新 更多