我找到了一个解决方案来隐藏基本 url 以确保 NDK 保护 api。将 base64 编码的字符串保存在 cpp 文件中,并从 java 类中调用它并解码 base64。
在您的项目中包含 c++ (NDK) 支持。您可以将其包含到您的新项目或旧项目中。
你的 cpp 文件名可以是 (native-lib.cpp)
搜索在线 base64 编码器并编码您的基本网址。现在将编码字符串保存在 cpp 文件中
里面的cpp文件示例代码是这样的:
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_com_touhidapps_MyProject_utils_MyConstants_baseUrlFromJNI(JNIEnv *env, jobject) {
std::string mUrl = "aHR0cDovL2FwaS5leGFtcGxlLmNvbS8="; //"http://api.example.com/";
return env->NewStringUTF(mUrl.c_str());
}
在 MyConstants.java 类中:(我保存了所有 api url。)
// load c++ library
static {
System.loadLibrary("native-lib");
}
public static native String baseUrlFromJNI();
// decode base64 to a string and get normal url
public static String getSecureBaseUrl() {
String mUrl = baseUrlFromJNI();
try {
String text = new String(Base64.decode(mUrl, Base64.DEFAULT), "UTF-8");
return text;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mUrl = "http://demo.example.com/"; // don't change this link. This will not execute normally, if exception happens then it will return a demo url.
return mUrl;
}
现在您可以获得如下所示的原始网址:
public static final String API_BASE = "" + getSecureBaseUrl();