Saturday, 17 June 2017

android - How to HTTP request by POST method with Kotlin




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.


Answer



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


}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...