kotlin实现网络连接
时间: 2024-01-23 22:09:25 浏览: 28
要使用Kotlin实现网络连接,可以使用Kotlin中的标准库中提供的java.net包或者OkHttp库。
使用java.net包:
```
import java.net.*
import java.io.*
fun main() {
val url: URL = URL("https://www.example.com")
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
conn.requestMethod = "GET"
val reader = BufferedReader(InputStreamReader(conn.inputStream))
var inputLine: String?
while (reader.readLine().also { inputLine = it } != null) {
println(inputLine)
}
reader.close()
}
```
使用OkHttp库:
```
import okhttp3.*
import java.io.IOException
fun main() {
val client = OkHttpClient()
val request = Request.Builder()
.url("https://www.example.com")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
println(response.body()?.string())
}
})
}
```
以上两种方式都可以实现Kotlin的网络连接。