去年接手pad端开发时曾问过其它组的老安卓一个问题,我们的安卓项目本地开发时能否调用本地接口,回答是否定的。也许是由于通用底座加入的限制,也许是因为太忙了,不想给我解释繁琐的解决方案。
那么在个人PC上玩耍总是能够调用本地接口的吧?同时考虑到先前做vue项目时能够通过修改前端的代理配置决定线上或线下接口,于是以安卓调用本地接口引出base_url的配置思路
单纯访问本地后端
开启明文通信
在 res/xml/network_security_config.xml
中允许明文通信:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">10.0.2.2</domain>
</domain-config>
</network-security-config>
在 AndroidManifest.xml 中引用该配置:
<application
android:networkSecurityConfig="@xml/network_security_config"
... >
...
</application>
使用OkHttp定义请求
引入okhttp以及gson依赖(如果已有则不需要处理)
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
implementation 'com.google.code.gson:gson:2.8.9'
}
定义PublicRepository
管理请求调用处, getUserList
用于获取用户列表信息,返回调用的callback,由调用处进行回调的解析
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
/**
* @author PineTree
* @description: TODO
* @date 2025/3/15 14:25
*/
public class PublicRepository {
private static volatile PublicRepository instance;
private PublicRepository() {
}
public static PublicRepository getInstance() {
if (instance == null) {
synchronized (PublicRepository.class) {
if (instance == null) {
instance = new PublicRepository();
}
}
}
return instance;
}
public void getUserList(Callback callback) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://10.0.2.2:8888/user/list")
.build();
client.newCall(request).enqueue(callback);
}
}
调用请求验证
PublicRepository.getInstance().getUserList(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
String hehe = "111";
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if (response.isSuccessful() && ObjectUtils.isNotEmpty(response.body())) {
Gson gson = new Gson();
List<UserVO> userVOS = gson.fromJson(response.body().string(), new TypeToken<List<UserVO>>() {}.getType());
System.out.println("response.body() = " + userVOS);
}
}
});
加入base_url
管理
考虑到每个请求都将IP、端口号等这些随环境变化的动态参数都写在url显得不优雅,于是引入了base_url
定义base_url
在模块的build.gradle
中添加构建配置信息,默认为debug
defaultConfig {
buildConfigField "String", "APP_ENV", "\"${project.hasProperty('APP_ENV') ? project.property('APP_ENV') : 'debug'}\""
}
如果com.android.tools.build:gradle:
为8+,还需要添加android.buildFeatures.buildConfig
设置为true
buildFeatures {
viewBinding true
buildConfig true
}
新建url管理类
新建类UrlManage,在getBaseUrl方法中获取构建信息参数BuildConfig.APP_ENV
,进而决定返回哪个环境的url
(真实项目一般采用类似思路获取需要路由的网关)
package com.example.myapplication1_java.util;
import com.example.myapplication1_java.BuildConfig;
import com.example.myapplication1_java.repository.PublicRepository;
/**
* @author PineTree
* @description: url管理
* @date 2025/3/16 19:45
*/
public class UrlManage {
private static volatile UrlManage instance;
private UrlManage() {
}
public static UrlManage getInstance() {
if (instance == null) {
synchronized (PublicRepository.class) {
if (instance == null) {
instance = new UrlManage();
}
}
}
return instance;
}
public String getBaseUrl() {
String appEnv = BuildConfig.APP_ENV;
String baseUrl = "";
switch (appEnv) {
case "debug":
baseUrl = "http://10.0.2.2:8888/";
break;
case "dev":
baseUrl = "http://dev:8888/";
break;
case "sit":
baseUrl = "http://sit:8888/";
break;
case "uat":
baseUrl = "http://uat:8888/";
break;
}
return baseUrl;
}
}
调整OkHttp定义请求
import com.example.myapplication1_java.util.UrlManage;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
/**
* @author PineTree
* @description: TODO
* @date 2025/3/15 14:25
*/
public class PublicRepository {
...
public void getUserList(Callback callback) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(UrlManage.getInstance().getBaseUrl() + "user/list")
.build();
client.newCall(request).enqueue(callback);
}
}
验证默认base_url
生效
验证修改base_url
生效
修改APP_ENV为uat,验证base_url
切换生效,在控制台执行下面指令
# 切换到模块目录
cd app
# clean旧的构建
gradle clean
# 生成 debug APK 设置APP_ENV为uat
gradle assembleDebug -PAPP_ENV=uat
# 上传APK
adb install -r build/outputs/apk/debug/app-debug.apk
# 启动应用
adb shell am start -n com.example.myapplication1_java/.MainActivity
由于本地并没有uat环境接口,解析不了uat请求会报错
总结
通过以上的配置,就能访问本地测试,并进行base_url
的统一管理了,该博客适用于个人demo验证,仅供参考。
代码见https://gitee.com/pinetree-cpu/android_demo_test