如何使用 Kotlin 通过 POST 方法进行 HTTP 请求

Khw*_*orn 5 android kotlin

我是 kotlin 开发人员。请教我在 Kotlin 中使用 httpRequest。

问题 - 如果我想请求 API 服务,并且必须使用 post 方法发送带有 json 对象的请求正文,我该怎么写??

感谢您的帮助。

esu*_*esu 5

您可以使用outputStream.write(postData).

 fun pushToChat(message: String) {

        val serverURL: String = "your URL"
        val url = URL(serverURL)
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "POST"
        connection.connectTimeout = 300000
        connection.connectTimeout = 300000
        connection.doOutput = true

        val postData: ByteArray = message.toByteArray(StandardCharsets.UTF_8)

        connection.setRequestProperty("charset", "utf-8")
        connection.setRequestProperty("Content-length", postData.size.toString())
        connection.setRequestProperty("Content-Type", "application/json")

        try {
            val outputStream: DataOutputStream = DataOutputStream(connection.outputStream)
            outputStream.write(postData)
            outputStream.flush()
        } catch (exception: Exception) {

        }

        if (connection.responseCode != HttpURLConnection.HTTP_OK && connection.responseCode != HttpURLConnection.HTTP_CREATED) {
            try {
                val inputStream: DataInputStream = DataInputStream(connection.inputStream)
                val reader: BufferedReader = BufferedReader(InputStreamReader(inputStream))
                val output: String = reader.readLine()

                println("There was error while connecting the chat $output")
                System.exit(0)

            } catch (exception: Exception) {
                throw Exception("Exception while push the notification  $exception.message")
            }
        }

    }
Run Code Online (Sandbox Code Playgroud)