如何从Kotlin应用中调用用于获取AD令牌的已部署Azure Function
Kotlin调用Azure Function获取AD令牌实现方案
以下实现完全对应你给出的JavaScript调用逻辑,支持异步回调、成功/失败分支处理。
方案1:使用OkHttp(JVM/安卓通用)
OkHttp是JVM生态最常用的HTTP客户端,安卓和后端服务都可以使用。
依赖配置(Gradle Kotlin DSL)
implementation("com.squareup.okhttp3:okhttp:4.12.0") // JSON解析可选依赖,可替换为Moshi等其他解析库 implementation("com.google.code.gson:gson:2.10.1")
实现代码
import okhttp3.* import com.google.gson.Gson import java.io.IOException // 对应接口返回的JSON结构,可根据实际返回字段调整 data class AdTokenResponse( val token: String ) private val okHttpClient = OkHttpClient() private val gson = Gson() fun getTokenAzure( onSuccess: (AdTokenResponse) -> Unit, onError: (String) -> Unit ) { val tokenUrl = "https://getadtokennet.azurewebsites.net/api/getadtokennet" val functionKey = "{你的函数密钥}" // 替换为实际的x-functions-key值 val request = Request.Builder() .url(tokenUrl) .addHeader("x-functions-key", functionKey) .get() .build() // 异步请求,不会阻塞当前线程 okHttpClient.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { val failureMessage = "GetToken error: ${e.message}" onError(failureMessage) println(failureMessage) } override fun onResponse(call: Call, response: Response) { if (!response.isSuccessful) { val failureMessage = "GetToken error: ${response.code} - ${response.message}" onError(failureMessage) println(failureMessage) return } runCatching { val responseBody = response.body?.string() ?: throw Exception("响应体为空") gson.fromJson(responseBody, AdTokenResponse::class.java) }.fold( onSuccess = { tokenResp -> onSuccess(tokenResp) println("token: ${tokenResp.token}") }, onFailure = { e -> val failureMessage = "GetToken error: 响应解析失败 - ${e.message}" onError(failureMessage) println(failureMessage) } ) } }) }
方案2:使用Ktor Client(支持多平台)
如果是Kotlin多平台项目,或者偏好协程风格的API,可以使用Ktor客户端。
依赖配置(Gradle Kotlin DSL)
implementation("io.ktor:ktor-client-core:2.3.7") // JVM/安卓引擎,多平台可替换为对应平台引擎 implementation("io.ktor:ktor-client-okhttp:2.3.7") // JSON解析依赖 implementation("io.ktor:ktor-client-content-negotiation:2.3.7") implementation("io.ktor:ktor-serialization-gson:2.3.7")
实现代码
import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.plugins.contentnegotiation.* import io.ktor.client.request.* import io.ktor.serialization.gson.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext private val ktorClient = HttpClient { install(ContentNegotiation) { gson() } } // 协程挂起函数,需要在协程作用域中调用 suspend fun getTokenAzure( onSuccess: (AdTokenResponse) -> Unit, onError: (String) -> Unit ) = withContext(Dispatchers.IO) { val tokenUrl = "https://getadtokennet.azurewebsites.net/api/getadtokennet" val functionKey = "{你的函数密钥}" // 替换为实际的x-functions-key值 runCatching { ktorClient.get<AdTokenResponse>(tokenUrl) { header("x-functions-key", functionKey) } }.fold( onSuccess = { tokenResp -> onSuccess(tokenResp) println("token: ${tokenResp.token}") }, onFailure = { e -> val failureMessage = "GetToken error: ${e.message}" onError(failureMessage) println(failureMessage) } ) }
注意事项
- 不要将函数密钥硬编码在生产代码中,安卓端建议使用安全存储保管密钥,服务端建议从环境变量、配置中心读取密钥
- 安卓端调用时需要提前声明
INTERNET权限,网络请求回调如果需要更新UI,需要自行切换到主线程执行 - 如果接口返回的JSON结构和示例不同,调整
AdTokenResponse数据类的字段定义即可
内容的提问来源于stack exchange,提问作者Cristobal BL
相关产品推荐
相关产品推荐

