【问题标题】:Retrofit body request is blank with Retrofit, when I use proguard and enable minify and shrinkresources当我使用proguard并启用minify和shrinkresources时,Retrofit body request是空白的
【发布时间】:2020-01-03 08:38:17
【问题描述】:

当我将minifyEnabled & shrinkResources 设置为true 时,发送的Retrofit body JSON 请求是空白的,当它设置为false 时,它​​可以正常工作。

我已经发布了整个 gradle 文件,所以你可以帮助我告诉我做错了什么。

当minifyEnabled & shrinkResources 是true 时,我的改造请求json 正文是这样的:

{}

当minifyEnabled & shrinkResources 是false 时它工作正常:

{"Data":"demoToken","Key":"demokey","Token":"2a9a8677-ac79-49d6-9947-d797b3e4d8e5"}

我的 gradle 看起来像这样:

   apply {
    plugin 'com.android.application'
    plugin 'kotlin-android'
    plugin 'kotlin-android-extensions'
    plugin 'kotlin-kapt'
    plugin 'io.fabric'
    plugin 'com.google.firebase.firebase-perf'
}
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.something.theapp"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 43 
        versionName "0.6.7"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        flavorDimensions "server"
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath = true
            }
        }
    }
    signingConfigs {
        kaira {
            storeFile file('key_tts.jks')
            storePassword 'android'
            keyAlias 'tts_key'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.kaira
            minifyEnabled true
            shrinkResources true
            buildConfigField "boolean", "ALLOW_DATABASE", "false"
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            signingConfig signingConfigs.kaira
            minifyEnabled true
            shrinkResources true
            buildConfigField "boolean", "ALLOW_DATABASE", "false"
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    productFlavors {
        local {
            //buildConfigField "String", "WebServiceUrl", "\"http://192.168.1.136:6264/siteapp/api/\""
//            buildConfigField "String", "WebServiceUrl", "\"http://192.168.1.21:5678/api/\""
            //   buildConfigField "String", "WebServiceUrl", "\"http://192.168.1.233:5677/api/\""
            //  buildConfigField "String", "WebServiceUrl", "\"http://192.168.1.26:5678/api/\""
            //buildConfigField "String", "WebServiceUrl", "\"http://192.168.1.25:5678/api/\""
//            buildConfigField "String", "WebServiceUrl", "\"http://192.168.1.37:5678/api/\""
//            buildConfigField "String", "WebServiceUrl", "\"https://api.forsell.in/api/\""
            //  buildConfigField "String", "WebServiceUrl", "\"http://192.168.1.23:5678/api/\""
            buildConfigField "String", "WebServiceUrl", "\"http://192.168.1.29:5678/api/\""
            buildConfigField "String", "WebUrl", "\"https://someurl.in/\""
            buildConfigField "String", "ServerName", "\"-Local\""
            dimension "server"
            copy {
                from "src/local"
                include "google-services.json"
                into "."
            }
        }
        temp {
            buildConfigField "String", "WebServiceUrl", "\"http://api.lezza.in/api/\""
            buildConfigField "String", "WebUrl", "\"https://someurl.in/\""
            buildConfigField "String", "ServerName", "\"-Local\""
            dimension "server"
            copy {
                from "src/local"
                include "google-services.json"
                into "."
            }
        }
        live {
            buildConfigField "String", "WebServiceUrl", "\"https://api.someurl.in/api/\""
            buildConfigField "String", "WebUrl", "\"https://someurl.in/\""
            buildConfigField "String", "ExtClientNameNew", "\"ExtClientName:TTS\""
            dimension "server"
            copy {
                from "src/livegcm"
                include "google-services.json"
                into "."
            }
        }
        staging {
            //buildConfigField "String", "WebServiceUrl", "\"http://192.168.1.233:85/api/\""//sunil
            //     buildConfigField "String", "WebServiceUrl", "\"http://192.168.1.233:5677/api/\""//devang
            //   buildConfigField "String", "WebServiceUrl", "\"http://192.168.1.233:85/api/\""
            buildConfigField "String", "WebServiceUrl", "\"https://stageapi.someurl.in/api/\""
            buildConfigField "String", "WebUrl", "\"https://stageweb.someurl.in/\""
            buildConfigField "String", "ServerName", "\"-Staging\""
            dimension "server"
            copy {
                from "src/local"
                include "google-services.json"
                into "."
            }
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
    dexOptions {
        preDexLibraries = false
        javaMaxHeapSize "4g" // 2g should be also OK
    }
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
    lintOptions {
        abortOnError false
        disable 'MissingTranslation'
    }
}
repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }
}

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '28.0.0'
            }
        }
    }
}
dependencies {
    def lifecycle_version = "2.0.0"
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation "android.arch.lifecycle:extensions:$lifecycle_version"
    annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.vectordrawable:vectordrawable:1.0.0-alpha1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.2') {
        exclude group: 'com.google.code.findbugs'
    }
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.okhttp3:okhttp:3.12.1'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation 'com.github.bumptech.glide:glide:4.5.0'
    implementation 'com.karumi:dexter:5.0.0'
    implementation 'com.google.android.gms:play-services-maps:16.1.0'
    implementation 'com.google.android.gms:play-services-location:16.0.0'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
    implementation 'org.jetbrains.anko:anko-common:0.9'
    implementation 'com.google.android.gms:play-services-ads:17.2.0'
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation project(path: ':imagepicker')
    implementation 'androidx.percentlayout:percentlayout:1.0.0'
    implementation 'com.google.firebase:firebase-core:16.0.9'
    implementation 'com.google.firebase:firebase-inappmessaging-display:17.2.0'
    implementation 'com.google.firebase:firebase-messaging:18.0.0'
    implementation 'com.google.firebase:firebase-config:17.0.0'
    implementation 'com.google.firebase:firebase-perf:17.0.2'
    implementation 'com.github.chrisbanes:PhotoView:2.3.0'
    implementation 'com.google.android.gms:play-services-places:16.1.0'
    implementation 'com.google.android.libraries.places:places:1.1.0'
    api 'com.theartofdev.edmodo:android-image-cropper:2.8.+'
    implementation 'com.github.faruktoptas:RetrofitRssConverterFactory:0.1.0'
    implementation 'com.wang.avi:library:2.1.3'
    implementation 'com.facebook.android:facebook-android-sdk:5.4.0'
    implementation('com.crashlytics.sdk.android:crashlytics:2.9.8@aar') {
        transitive = true
    }
    implementation 'com.haozhang.libary:android-slanted-textview:1.2'
    implementation 'com.facebook.shimmer:shimmer:0.4.0'
    implementation 'com.github.freshdesk:freshchat-android:1.5.3'
    implementation 'commons-io:commons-io:2.4'
    implementation 'com.getkeepsafe.taptargetview:taptargetview:1.12.0'
    implementation 'com.razorpay:checkout:1.5.6'
    implementation 'com.google.android.gms:play-services-analytics:17.0.0'

}
apply plugin: 'com.google.gms.google-services'

下面是我的主要模型类

class ServiceRequest {

    var Key: String? = "SiteAdminAppkey"
    var Token: String? = ""
    //    var Slug: String? = "admin"
    var Data: Any? = null
}

我可以通过添加 @SerializeName 注释来完成这项工作,但我必须在每个模型类中都这样做。在我的另一个项目中,Proguard 和一切都无需序列化即可工作。

【问题讨论】:

  • 你能添加你的模型以及如何序列化它们吗?
  • 这不可能是因为shrink resources和minify enable与json无关
  • @ShivamOberoi 这是改造请求正文
  • @Fred 我不序列化它。即使没有它,它也能正常工作。在其他项目中,我没有遇到这个问题。
  • 启用 Minify 可能会影响 json 序列化。如果您忘记添加注释来序列化具有特定名称的属性,它们将使用混淆名称进行序列化。也许,它们甚至被从代码中剥离,这就是你看不到它们的原因。我要求模型看看你是如何定义它们的,如果你也检查一下 proguard 配置会很好。

标签: android gradle retrofit proguard minify


【解决方案1】:

在您的proguard-rules.pro 文件中添加以下行

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

还在 gradle.properties 文件中添加以下行。

android.enableR8=false

我面临同样的问题,并在文件中添加了上面的行,它对我有用。

【讨论】:

  • 那么您提到的要添加到 proguard 中的代码已经存在。但是,当我添加 gradle.properties 行并且它起作用了。禁用 R8 是否安全?我对此一无所知。请告诉我。
  • 您应该尝试保持启用 R8。最终 ProGuard 可能会被删除
  • Mehul Kabaria,有什么解释为什么我们需要保留 SerializedName 字段吗?
  • 我们为什么要禁用 R8?
  • 添加android.enableR8=false后gradle build一直运行
【解决方案2】:

在 proguard-rules 中添加以下行

-keepclassmembers class <yourpackagename>.** { <fields>; }

将 yourpackagename 替换为所有模型类所在的目录路径,例如我的情况

-keepclassmembers class com.demo.app.model.** { <fields>; }

【讨论】:

  • 谢谢你..你节省了我的时间......这对我有用
  • 你真的节省了我的时间。我进行了很多搜索,但您的解决方案对我有用。谢谢大佬!!!
  • 是的,这是您需要的最佳答案,因为当我们 manifyEnabled 为 true 时,字段成员变得不可读并且与我们期望的 API 请求不同
【解决方案3】:

这对我有用。

# Retrofit2
-keepclasseswithmembers class * {
    @retrofit2.http.* <methods>;
}
-keepclassmembernames interface * {
    @retrofit2.http.* <methods>;
}

# GSON Annotations
-keepclassmembers,allowobfuscation class * {
  @com.google.gson.annotations.SerializedName <fields>;
}

由于某种原因,如果没有 GSON 注释设置,它就无法工作,即使直接在模型类上添加 @Keep 注释也是如此。

【讨论】:

  • 这适用于 Header, query , body parameters for retrofit??
【解决方案4】:

由于您使用 Gson 将 Json 转换为您的模型,因此您需要确保反射在这些类上正常工作(因为我假设您没有t 为这些创建了一个自定义适配器)。

保留类名和字段名的最简单方法,您可以使用AndroidX Annotations 中的@Keep 注释模型:

表示在构建时缩小代码时不应删除带注释的元素。这通常用于仅通过反射访问的方法和类,因此编译器可能会认为代码未使用。

【讨论】:

  • 这是关于你的模型的成员。 AndroidX 仅在它提供 @Keep 注释时才有意义。如果你提供你的模型,我可以提供一个例子。
【解决方案5】:

这是一个更新的答案(05/20),因为在我的情况下似乎没有任何效果。

  1. 使用 Retrofit 文档 here 中的 Proguard 规则。

  2. 让你的模型类像 Chouhan 一样回答。

【讨论】:

    【解决方案6】:
    • 使用最新版本的改造库: com.squareup.retrofit2:retrofit:2.7.1 如果您使用的是 R8,则会自动包含收缩和混淆规则。 Latest Retrofit lib

    • 此外,Gson 实现的更改“com.google.code.gson:gson:2.8.6” Latest GSON lib

    • 检查 R8 兼容性-常见问题解答r8-compatibility-faq for GSON

    • 如果您使用的是 OkHttp3,请更改为最新版本 okhttp3LibVersion = '4.3.1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      • 2015-11-16
      相关资源
      最近更新 更多