当前位置:首页 > 行业动态 > 正文

安卓开发动态获取域名

动态获取域名的必要性

在安卓开发中,动态获取域名常用于以下场景:

  • 多环境切换(开发/测试/生产)
  • 灰度发布(不同用户访问不同版本服务)
  • 地域优化(根据用户IP选择最近CDN节点)
  • 规避风控(动态更换被屏蔽的域名)

实现方案与代码示例

配置文件动态加载

原理:将域名存储在本地配置文件(如JSON/XML),运行时读取。

// assets/config.json
{
  "domain": "https://api.example.com"
}
// 读取代码
public String getDomainFromAssets(Context context) {
    try {
        InputStream is = context.getAssets().open("config.json");
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        String json = new String(buffer, "UTF-8");
        JSONObject obj = new JSONObject(json);
        return obj.getString("domain");
    } catch (Exception e) {
        e.printStackTrace();
        return "https://default.com"; // 默认值
    }
}

优点:简单易实现,无需网络请求
缺点:需重新打包更新配置,不适合高频变动场景


网络请求动态获取

原理:通过远程接口获取最新域名配置。

// Retrofit接口定义
@GET("config/domain")
Call<DomainConfig> getDomainConfig();
// 使用示例
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://config-server.com/")
    .build();
ApiService service = retrofit.create(ApiService.class);
service.getDomainConfig().enqueue(new Callback<DomainConfig>() {
    @Override
    public void onResponse(Call<DomainConfig> call, Response<DomainConfig> response) {
        String domain = response.body().getDomain();
        // 更新网络请求的baseUrl
    }
    @Override
    public void onFailure(Call<DomainConfig> call, Throwable t) {
        // 错误处理
    }
});

优点:配置可实时更新
缺点:依赖网络,首次启动可能延迟


远程配置服务(Firebase Remote Config)

原理:利用Firebase配置服务管理域名参数。

// 初始化Remote Config
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
    .setDeveloperModeEnabled(BuildConfig.DEBUG)
    .build();
mFirebaseRemoteConfig.setConfigSettings(configSettings);
// 获取域名
String domain = mFirebaseRemoteConfig.getString("app_domain");

优点:可视化控制台管理,支持AB测试
缺点:需集成Firebase SDK,国内网络可能受限


WebView加载HTML配置

原理:将域名配置写入HTML文件,通过WebView解析。

<!-assets/config.html -->
<html>
  <body>
    <script>
      window.domain = "https://dynamic.example.com";
    </script>
  </body>
</html>
// 读取代码
WebView webView = new WebView(context);
webView.loadUrl("file:///android_asset/config.html");
webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        String domain = view.evaluateJavascript("window.domain") + "";
        // 使用domain进行网络请求
    }
});

优点:可嵌入复杂逻辑(如加密配置)
缺点:性能开销较大,存在跨域安全问题


方案对比表

方案 实时性 实现难度 维护成本 适用场景
本地配置文件 固定环境切换
网络请求 高频变动场景
Firebase配置 多版本控制
WebView 特殊安全需求

常见问题与解答

Q1:如何缓存动态域名避免重复请求?

A1
使用本地存储(如SP或MMKV)缓存域名,设置过期时间。

// 读取缓存
String cachedDomain = SPUtils.getString("domain", null);
if (cachedDomain != null && !isExpired()) {
    return cachedDomain;
}
// 发起网络请求获取新域名...

Q2:动态域名如何通过HTTPS验证?

A2
若域名不固定,需配置Network Security Config

  1. res/xml/network_security_config.xml添加:
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">.example.com</domain>
    </domain-config>
  2. AndroidManifest.xml引用:
    <application ...>
        <network-security-config android:resource="@xml/network_security_config" />
    </application>

    此配置允许所有example.com子域名的明文通信,实际使用中建议配合证书