Kotlin Android中JsonObjectRequest调用Request.Method.Get失败求助
解决Kotlin Android中Volley的JsonObjectRequest无法识别Request.Method.Get的问题
问题根源
你代码里的Request类导入错误——当前导入的是android.app.DownloadManager.Request(系统下载管理器的请求类),和Volley库的Request类完全无关,所以找不到Volley的请求方法常量。另外Volley中的GET请求常量是大写的GET,而非你写的Get。
修复步骤
删除无用且冲突的导入语句:
import android.app.DownloadManager.Requestimport androidx.privacysandbox.tools.core.model.Method- 未用到的
import android.app.DownloadManager也可一并删除
导入Volley官方的
Request类:import com.android.volley.Request将代码中的
Request.Method.Get修改为Request.Method.GET
修正后的完整代码
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.Volley class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val username = findViewById<EditText>(R.id.etUserName) val password = findViewById<EditText>(R.id.etPassword) val btn = findViewById<Button>(R.id.button) btn.setOnClickListener { val url = "http://www.sepehrfarm.ir/app/read.php?username=${username.text.toString()}&password=${password.text.toString()}" val req: RequestQueue = Volley.newRequestQueue(this) val jos = JsonObjectRequest( Request.Method.GET, url, null, Response.Listener { response -> Toast.makeText(this, "记录已添加", Toast.LENGTH_LONG).show() }, Response.ErrorListener { error -> // 建议添加错误处理,方便排查问题 Toast.makeText(this, "请求失败:${error.message}", Toast.LENGTH_LONG).show() } ) // 必须将请求加入队列才会执行 req.add(jos) } } }
额外提示
- 原代码遗漏了
req.add(jos),即使修复了导入问题,请求也不会执行 - 用字符串模板拼接URL比直接用
+更简洁易读 - 错误回调中添加处理逻辑,能快速定位请求失败原因
内容的提问来源于stack exchange,提问作者Amir Elahi
相关产品推荐
相关产品推荐

