1

From my Android/Kotlin app I need to make requests to a backend REST API. I need to send along a JWT for auth. I'm currently using code like this that I shamelessly copied from this answer: https://stackoverflow.com/a/46179139/3267158

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())
        }
    }
}

But I'm not married to this code if there is a better way using facilities readily available in Android/Kotlin.

Can someone show me some simple code that makes an HTTP PUT or GET request and including a JWT in the header.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
Michael
  • 55
  • 1
  • 8

1 Answers1

2

I would not recommend to do HTTP requests "manually". Instead, take a look at the HTTP Client libraries available for/in Kotlin. It will make your life much easier. Here's an example using kohttp:

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

    header {
        "Authorization" to "YOUR JWT"
    }
}
Sergei Rybalkin
  • 3,337
  • 1
  • 14
  • 27
seg
  • 1,398
  • 1
  • 11
  • 18