Android-Kotlin:通过GET或PUT请求发送JWT

时间:2018-12-24 02:41:09

标签: android http kotlin jwt

我需要通过我的Android/Kotlin应用向后端REST API发出请求。我需要为JWT发送auth。我目前正在使用从answer

private fun sendGet() {
    val url = "http://www.google.com/"
    val obj = URL(url)

    with(obj.openConnection() as HttpURLConnection) {
        // optional default is GET
        requestMethod = "GET"


        println("\nSending 'GET' request to URL : $url")
        println("Response Code : $responseCode")

        BufferedReader(InputStreamReader(inputStream)).use {
            val response = StringBuffer()

            var inputLine = it.readLine()
            while (inputLine != null) {
                response.append(inputLine)
                inputLine = it.readLine()
            }
            println(response.toString())
        }
    }
}

但是,如果有一种更好的方法来使用Android/Kotlin中现成的功能,那么我不喜欢此代码。

有人可以向我展示一些简单的代码,这些代码发出HTTP PUTGET请求,并且在标头中包含JWT

1 个答案:

答案 0 :(得分:1)

我不建议“手动”执行HTTP请求。相反,请查看Kotlin中可用的HTTP Client libraries。这将使您的生活更加轻松。这是使用kohttp的示例:

val response: Response = httpGet {
    host = "bla.com"
    path = "/yourpath"

    header {
        "Authorization" to "YOUR JWT"
    }
}