HTTP Request in Kotlin

后端 未结 11 2475
不知归路
不知归路 2020-11-28 06:59

I\'m completely new to Kotlin. I want to do a login validation using POST method and to get some information using GET method. I\'ve URL, server Username and Password alread

11条回答
  •  孤城傲影
    2020-11-28 07:29

    Without adding additional dependencies, this works. You don't need Volley for this. This works using the current version of Kotlin as of Dec 2018: Kotlin 1.3.10

    If using Android Studio, you'll need to add this declaration in your AndroidManifest.xml:

    
    
    

    You should manually declare imports here. The auto-import tool caused me many conflicts.:

    import android.os.AsyncTask
    import java.io.BufferedReader
    import java.io.InputStreamReader
    import java.io.OutputStream
    import java.io.OutputStreamWriter
    import java.net.URL
    import java.net.URLEncoder
    import javax.net.ssl.HttpsURLConnection
    

    You can't perform network requests on a background thread. You must subclass AsyncTask.

    To call the method:

    NetworkTask().execute(requestURL, queryString)
    

    Declaration:

    private class NetworkTask : AsyncTask() {
        override fun doInBackground(vararg parts: String): Long? {
            val requestURL = parts.first()
            val queryString = parts.last()
    
            // Set up request
            val connection: HttpsURLConnection = URL(requestURL).openConnection() as HttpsURLConnection
            // Default is GET so you must override this for post
            connection.requestMethod = "POST"
            // To send a post body, output must be true
            connection.doOutput = true
            // Create the stream
            val outputStream: OutputStream = connection.outputStream
            // Create a writer container to pass the output over the stream
            val outputWriter = OutputStreamWriter(outputStream)
            // Add the string to the writer container
            outputWriter.write(queryString)
            // Send the data
            outputWriter.flush()
    
            // Create an input stream to read the response
            val inputStream = BufferedReader(InputStreamReader(connection.inputStream)).use {
                // Container for input stream data
                val response = StringBuffer()
                var inputLine = it.readLine()
                // Add each line to the response container
                while (inputLine != null) {
                    response.append(inputLine)
                    inputLine = it.readLine()
                }
                it.close()
                // TODO: Add main thread callback to parse response
                println(">>>> Response: $response")
            }
            connection.disconnect()
    
            return 0
        }
    
        protected fun onProgressUpdate(vararg progress: Int) {
        }
    
        override fun onPostExecute(result: Long?) {
        }
    }
    

提交回复
热议问题