【问题标题】:Avoiding hardcoded ip addresses in Android避免在 Android 中硬编码 IP 地址
【发布时间】:2017-07-07 05:54:27
【问题描述】:

我在我的android项目中使用下面的方法来存储服务器ip地址,以便其他类可以访问服务器url。

   interface GlobalConstants{
       String SERVER_URL = "192.168.xx.xx";
   }

但是,这种方法需要在每次 IP 地址更改时重新编译,并且反编译会暴露服务器 url。有没有更好的方法来初始化 SERVER_URL ?

我尝试了 System.setProperty() 和 System.getProperty() 但它仍然在运行时完成。有没有办法使用配置文件之类的东西来存储 IP 地址并使其可配置?

提前致谢。 :)

【问题讨论】:

  • 我认为你没有办法绕过apk的编译和构建。
  • 为什么你不只是使用 DNS?
  • @chrylis 这是通过 wifi 访问 PC 的 localhost 来测试代码的尝试。

标签: java android security hardcoded


【解决方案1】:

你可以在 gradle.build 中做到这一点

 buildTypes {
        debug {
            buildConfigField "String", "SERVER_URL", "\"http:TempRequest\""
        }
        release {
            buildConfigField "String", "SERVER_URL", "\"http:TempRequest\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

然后你可以使用 android studio 生成的BuildConfig 类来访问它。

例如

String url = BuildConfig.SERVER_URL + "endpoint";

希望对你有所帮助。

【讨论】:

  • 这是我一直在寻找的,虽然它并没有消除重新编译的需要。谢谢。
猜你喜欢
  • 2018-06-09
  • 1970-01-01
  • 1970-01-01
  • 2011-01-07
  • 1970-01-01
  • 2022-10-31
  • 1970-01-01
  • 1970-01-01
  • 2011-05-01
相关资源
最近更新 更多