Android Kotlin - Volley 意外响应代码 400

Android Kotlin - Volley Unexpected response code 400

我使用 Django 制作了 REST API,现在我想将它连接到 android。我正在使用 Kotlin 和 Volley 库。我创建了代码,但仍然收到此错误:

E/Volley: [287] BasicNetwork.performRequest: Unexpected response code 400 for http://laude.ct8.pl/api/user/login/.

这是我的 Kotlin 代码:

        val jsonObj = JSONObject()

        val LOGIN_API_URL = "http://laude.ct8.pl/api/user/login/"

        loginBtn.setOnClickListener {
            jsonObj.put("username", username.text)
            jsonObj.put("password", passwd.text)

            val que = Volley.newRequestQueue(this@MainActivity)
            val req = JsonObjectRequest(Request.Method.POST, LOGIN_API_URL,
                    Response.Listener {
                        response ->
                        Toast.makeText(this@MainActivity, response.toString(), Toast.LENGTH_LONG).show()
                    },
                    Response.ErrorListener {
                        error ->
                        Toast.makeText(this@MainActivity, error.toString(), Toast.LENGTH_LONG).show()
                    })

            que.add(req)

        }

我看到 Content-Type 可能会出现问题,所以我尝试使用这一行,我将其添加到 jsonObj.put("password", passwd.text) 下。

这是这一行: jsonObj.put("Content-Type", "application/json").

这里是一些测试登录数据:

username: testUser1232

password: test123123

非常感谢您的帮助!

当您创建 JsonObjectRequest 时,您不会将 jsonObj 传递给它。

尝试:

val req = JsonObjectRequest(Request.Method.POST, LOGIN_API_URL, jsonObj,
                    Response.Listener {
                        response ->
                        Toast.makeText(this@MainActivity, response.toString(), Toast.LENGTH_LONG).show()
                    },
                    Response.ErrorListener {
                        error ->
                        Toast.makeText(this@MainActivity, error.toString(), Toast.LENGTH_LONG).show()
                    })