如何使用Kotlin通过POST方法进行HTTP请求 [英] How to HTTP request by POST method with Kotlin

查看:3882
本文介绍了如何使用Kotlin通过POST方法进行HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new a kotlin dev. please teach me to use httpRequest in Kotlin.

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

Question - If I want to request to API service and I must to send request body with json object by use post method, How I write??

感谢帮助.

推荐答案

您可以使用outputStream.write(postData)写入数据.

You can write your data using 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-lenght", 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")
            }
        }

    }

这篇关于如何使用Kotlin通过POST方法进行HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆