使用 Kotlin 在 Android 中进行 HTTP 请求 [英] HTTP Request in Android with Kotlin

查看:66
本文介绍了使用 Kotlin 在 Android 中进行 HTTP 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 POST 方法进行登录验证并使用 GET 方法获取一些信息.

I want to do a login validation using POST method and to get some information using GET method.

我已经有了上一个项目的 URL、服务器用户名和密码.

I've URL, server Username and Password already of my previous project.

推荐答案

对于 Android,Volley 是开始的好地方.对于所有平台,您可能还想查看 ktor 客户端或 http4k 都是不错的库.

For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client or http4k which are both good libraries.

但是,您也可以使用标准 Java 库,例如 java.net.HttpURLConnection这是 Java SDK 的一部分:

However, you can also use standard Java libraries like java.net.HttpURLConnection which is part of the Java SDK:

fun sendGet() {
    val url = URL("http://www.google.com/")

    with(url.openConnection() as HttpURLConnection) {
        requestMethod = "GET"  // optional default is GET

        println("
Sent 'GET' request to URL : $url; Response Code : $responseCode")

        inputStream.bufferedReader().use {
            it.lines().forEach { line ->
                println(line)
            }
        }
    }
}

或者更简单:

URL("https://google.com").readText()

这篇关于使用 Kotlin 在 Android 中进行 HTTP 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆