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
相关产品推荐
相关产品推荐

