Issue
I'm new a kotlin dev. please teach me to use httpRequest in Kotlin.
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??
Thank for help.
Solution
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.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")
}
}
}
Answered By - esu