android 如何使用Kotlin为Python API指定参数?

s5a0g9ez  于 2023-01-24  发布在  Android
关注(0)|答案(1)|浏览(158)

我做了一个python API,我试图让我的应用程序连接到它,但是对于登录功能,我需要发送用户名和密码,但我不知道该怎么做。

username = data.get('username')
        email = data.get('email')
        password = data.get('password')

还有《Kotlin法典》

private fun sendData(username:String, password:String): Thread {
        return Thread {
            val url = URL("https://127.0.0.1:5000/login")
            val connection = url.openConnection() as HttpsURLConnection
            connection.setRequestProperty("username", username)
            connection.setRequestProperty("password", password)
            if (connection.responseCode == 200) {
                val inputSystem = connection.inputStream
                println(inputSystem.toString())
                Toast.makeText(applicationContext, "It worked", Toast.LENGTH_SHORT).show()
            }
            else {
                var code: String = "ERROR"
                Toast.makeText(applicationContext, "NO CONNECTION", Toast.LENGTH_SHORT).show()
            }
        }
    }

连接是打开的,但我可以得到任何数据,我还没有尝试任何东西,因为我找不到关于这方面的好文档。

00jrzges

00jrzges1#

例如,您可以首先设置一个类来处理凭据:

class LoginData(
    val userID: String,
    val pw: String
){

    /** Returns a hashmap of the data stored in the class object. */
    fun getHashmap(): Map<String,String> {
        val params = HashMap<String,String>()
        params["username"] = userID
        params["password"] = pw
        return params
    }

    /** Obtains a JSONObject of the data stored in the class object. */
    fun getJson(): JSONObject {
        val params = this.getHashmap()
        return JSONObject(params)
    }
}

然后,利用凌空(别忘了将其添加到您的构建等级:implementation 'com.android.volley:volley:1.2.0'),请执行以下操作:

fun sendData(username: String?, password: String?) {

    val url = "https://127.0.0.1:5000/login"

    var loginData = LoginData(
        userID = username!!,
        pw = password!!
    )
    val queue = Volley.newRequestQueue(this)
    val jsonRequest = JsonObjectRequest(
        Request.Method.POST,
        url,
        loginData.getJson(),
        Response.Listener {
                response -> handleResponse(response)//do something with the response
        },
        Response.ErrorListener { error -> println("That didn't work: $error")})
    queue.add(jsonRequest)

}

其中handleResponse()包含用于评估从服务器返回的内容的逻辑:

fun handleResponse(response: JSONObject) {
    //your evaluation logic
}

相关问题