You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin中Volley RequestQueue不工作的修复方法

问题修复

你的Volley没有发起请求是两个核心错误导致的:

  • URL格式不合法:你写的地址localhost/login/name/$name/password/$password缺少HTTP协议头,Volley无法识别合法请求地址,会直接拦截请求不会发送。另外注意:安卓模拟器里的localhost指向的是模拟器自身,不是你运行后端服务的电脑,访问本地调试的后端要把地址换成10.0.2.2;如果是真机调试,换成电脑在同一局域网下的实际IP即可。
  • 错误回调为空实现:你写的错误监听器是{ error -> {}},不会打印任何错误信息,就算请求构造、发送过程出问题,你也完全感知不到异常。

额外注意:如果你的targetSdkVersion >= 28(对应Android 9.0),系统默认禁止明文HTTP请求,要么给后端配置HTTPS证书,要么在AndroidManifest.xml的application标签下加android:usesCleartextTraffic="true"放开明文请求限制。


修复后的参考代码:

class LoginActivity : AppCompatActivity() {
    private lateinit var loginButton: Button
    private lateinit var loginNameEditText: EditText
    private lateinit var passwordEditText: EditText
    private lateinit var queue: RequestQueue

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        loginButton = findViewById(R.id.loginButton)
        loginNameEditText = findViewById(R.id.loginName)
        passwordEditText = findViewById(R.id.loginPW)
        // RequestQueue只需要初始化一次,不用每次点击按钮都新建
        queue = Volley.newRequestQueue(this)

        loginButton.setOnClickListener {
            val name = loginNameEditText.text.toString().trim()
            val password = passwordEditText.text.toString().trim()

            if (name.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "Check your input!", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            // 替换为你自己的后端服务端口,必须带http/https协议头
            val url = "http://10.0.2.2:8080/login/name/$name/password/$password"

            val stringRequest = StringRequest(Request.Method.POST,
                url,
                { response ->
                    println(response)
                    if (response == "0") {
                        finish()
                    } else {
                        Toast.makeText(this, "Incorrect name or password!", Toast.LENGTH_SHORT).show()
                    }
                },
                { error ->
                    // 不要写空回调,至少打印错误日志方便排查问题
                    error.printStackTrace()
                    Toast.makeText(this, "Request failed: ${error.message}", Toast.LENGTH_SHORT).show()
                }
            )

            stringRequest.setShouldCache(false)
            queue.add(stringRequest)
        }
    }
}

实践提醒:把账号密码直接拼在URL路径里的做法安全性很差,就算用POST请求也建议把参数放在请求体中传递,通过重写StringRequest的getParams()方法提交表单参数,不要把敏感信息明文拼接在地址上。


内容的提问来源于stack exchange,提问作者user13692250

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 18:27:34