Kotlin中的HTTP请求

我对Kotlin完全不熟悉。 我想使用POST方法进行登录validation,并使用GET方法获取一些信息。 我已经拥有了我之前项目的URL,服务器用户名和密码。 我没有find任何使用此东西的正确示例项目。 任何人都可以建议我在HTTP请求中使用GET和POST方法的任何工作示例

您可以使用在Java中使用的标准库。 例如HttpURLConnection

 private fun sendGet() { val url = "http://www.google.com/" val obj = URL(url) with(obj.openConnection() as HttpURLConnection) { // optional default is GET requestMethod = "GET" println("\nSending 'GET' request to URL : $url") println("Response Code : $responseCode") BufferedReader(InputStreamReader(inputStream)).use { val response = StringBuffer() var inputLine = it.readLine() while (inputLine != null) { response.append(inputLine) inputLine = it.readLine() } println(response.toString()) } } } 

这就是您可以将简单的HTTP请求发送到服务器的方式。 我建议使用Apache HttpComponents或者在复杂任务时使用的任何框架。 对于Android, Volley是一个开始的好地方。

 import java.io.IOException import java.net.URL fun main(vararg args: String) { val response = try { URL("http://seznam.cz") .openStream() .bufferedReader() .use { it.readText() } } catch (e: IOException) { "Error with ${e.message}." } println(response) } 

使用HttpURLConnection发送带有参数的HTTP POST / GET请求:

POST参数:

 fun sendPostRequest(userName:String, password:String) { var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8") reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") val mURL = URL("") with(mURL.openConnection() as HttpURLConnection) { // optional default is GET requestMethod = "POST" val wr = OutputStreamWriter(getOutputStream()); wr.write(reqParam); wr.flush(); println("URL : $url") println("Response Code : $responseCode") BufferedReader(InputStreamReader(inputStream)).use { val response = StringBuffer() var inputLine = it.readLine() while (inputLine != null) { response.append(inputLine) inputLine = it.readLine() } it.close() println("Response : $response") } } } 

使用参数获取:

 fun sendGetRequest(userName:String, password:String) { var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8") reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") val mURL = URL("?"+reqParam) with(mURL.openConnection() as HttpURLConnection) { // optional default is GET requestMethod = "GET" println("URL : $url") println("Response Code : $responseCode") BufferedReader(InputStreamReader(inputStream)).use { val response = StringBuffer() var inputLine = it.readLine() while (inputLine != null) { response.append(inputLine) inputLine = it.readLine() } it.close() println("Response : $response") } } }