HTTP Request in Kotlin

后端 未结 11 2467
不知归路
不知归路 2020-11-28 06:59

I\'m completely new to Kotlin. I want to do a login validation using POST method and to get some information using GET method. I\'ve URL, server Username and Password alread

11条回答
  •  攒了一身酷
    2020-11-28 07:30

    If you are using Kotlin, you might as well keep your code as succinct as possible. The run method turns the receiver into this and returns the value of the block. this as HttpURLConnection creates a smart cast. bufferedReader().readText() avoids a bunch of boilerplate code.

    return URL(url).run {
            openConnection().run {
                this as HttpURLConnection
                inputStream.bufferedReader().readText()
            }
    }
    

    You can also wrap this into an extension function.

    fun URL.getText(): String {
        return openConnection().run {
                    this as HttpURLConnection
                    inputStream.bufferedReader().readText()
                }
    }
    

    And call it like this

    return URL(url).getText()
    

    Finally, if you are super lazy, you can extend the String class instead.

    fun String.getUrlText(): String {
        return URL(this).run {
                openConnection().run {
                    this as HttpURLConnection
                    inputStream.bufferedReader().readText()
                }
        }
    }
    

    And call it like this

    return "http://somewhere.com".getUrlText()
    

提交回复
热议问题