Search This Blog

Friday, February 23, 2018

POST DATA TỪ APP LÊN SERVER - Kotlin

private fun postData(link: String?): String {
    val connect: HttpURLConnection
    var url: URL =  URL(link)
    try {
        connect = url.openConnection() as HttpURLConnection
        connect.readTimeout = 10000
        connect.connectTimeout = 15000
        connect.requestMethod = "POST"
        // POST theo tham số
        val builder = Uri.Builder()
                .appendQueryParameter("ten", "Đặng Minh Tiến")
                .appendQueryParameter("tuoi", "20")
        val query = builder.build().getEncodedQuery()
        val os = connect.outputStream
        val writer = BufferedWriter(OutputStreamWriter(os, "UTF-8"))
        writer.write(query)
        writer.flush()
        writer.close()
        os.close()
        connect.connect()
    } catch (e1: IOException) {
        e1.printStackTrace()
        return "Error!"
    }

    try {
        // Đọc nội dung trả về sau khi thực hiện POST
        val response_code = connect.responseCode
        if (response_code == HttpURLConnection.HTTP_OK) {
            val input = connect.inputStream
            val reader = BufferedReader(InputStreamReader(input))
            val result = StringBuilder()
            var line: String
            try {
                do{
                    line = reader.readLine()
                    if(line != null){
                        result.append(line)
                    }
                }while (line != null)

                reader.close()
            }catch (e:Exception){}

            return result.toString()
        } else {
            return "Error!"
        }
    } catch (e: IOException) {
        e.printStackTrace()
        return "Error!"
    } finally {
        connect.disconnect()
    }
}

No comments:

Post a Comment