如何从 Kotlin 调用 Azure 函数

How to call Azure function from Kotlin

我目前已经部署了一个用于获取 AD 令牌的 Azure 函数。

函数: https://getadtokennet.azurewebsites.net/api/getadtokennet

请求header:

x-functions-key = {键}

如何从我的 Kotlin 应用程序调用此函数?

这是我从Javascript

中调用它的方式
function getTokenAzure(onsuccess, onerror) {
    var tokenUrl = 'https://getadtokennet.azurewebsites.net/api/getadtokennet';

    $.ajax(tokenUrl, {
        method: 'GET',
        beforeSend: function (request) {
            request.setRequestHeader("x-functions-key", "function key");
        },
        success: function (data) {
            onsuccess(data);
            console.log('token: ' + data.token);
        },
        error: function (xhr, status, error) {
            var failureMessage = "GetToken error: " + status + " - " + error;
            onerror(failureMessage);
            console.log(failureMessage);
        }
    });
}
  1. 在 IntelliJ IDEA 中,select创建新项目
  2. New Project window, select Maven 左侧窗格中。
  3. Select Create from archetype 复选框,然后 select Add Archetype azure-functions-kotlin-archetype.
  4. Add Archetype window 中,完成以下字段:
    • GroupId: com.microsoft.azure
    • ArtifactId: azure-functions-kotlin-archetype
    • 版本:使用来自the central repository
    • 的最新版本
  5. Select 确定,然后select 下一步.
  6. 输入当前项目的详细信息,然后select 完成

有关完整信息,请参阅以下具有相同信息的链接。

Kotlin Function and Running Kotlin in Azure Functions

找到路了,就在这里

   fun getToken(): String {

        val tokenUrl = URL("https://getadtokennet.azurewebsites.net/api/getadtokennet")

        val connection = tokenUrl.openConnection() as HttpURLConnection
        connection.requestMethod = "POST"
        connection.setRequestProperty("x-functions-key", "function key")
        connection.doOutput = true

        val responseCode = connection.responseCode

        if (responseCode == HTTP_OK) {
            val readerIn = BufferedReader(InputStreamReader(connection.inputStream))
            var inputLine = readerIn.readLine()
            val response = StringBuffer()

            do {
                response.append(inputLine)
            } while (inputLine.length < 0)
            readerIn.close()

            // Return token
            return response.toString()
        } else {
            val responseError = Error(code = "BadRequest", message = "There was an error getting the token.")
            throw IOException(responseError.toString())
        }
    }