Android新手求助:如何将用户输入传入Volley POST请求的JSON体?
解决Volley POST请求无法传入用户输入的问题
你的问题核心是请求创建时机不对——在onCreate方法里,用户还没输入账号密码你就提前构建了请求体和StringRequest,这时候获取到的输入框内容是空字符串。点击按钮发送的是这个提前生成的、没有实际用户输入的请求,自然无法正确传递参数。
修正方案:
把请求的创建逻辑移到按钮的onClick事件中,这样每次用户点击登录时,才会获取当前输入框的最新内容,构建正确的请求体并发送。
修改后的完整代码:
public class LoginActivity extends AppCompatActivity { Button login_btn; EditText input_username, input_password; String url; RequestQueue queue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); login_btn = findViewById(R.id.btn_login); input_username=findViewById(R.id.editText_username); input_password=findViewById(R.id.editText_password); url="https://restful-booker.herokuapp.com/auth"; queue=Volley.newRequestQueue(this); login_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { JSONObject jsonBody = new JSONObject(); // 点击时才获取用户输入的内容 String username = input_username.getText().toString(); String password = input_password.getText().toString(); jsonBody.put("username", username); jsonBody.put("password", password); final String mRequestBody = jsonBody.toString(); StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Toast.makeText(LoginActivity.this, response,Toast.LENGTH_LONG).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(LoginActivity.this, error.toString(),Toast.LENGTH_LONG).show(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> header= new HashMap<>(); header.put ("accept","*/*"); header.put ("Content-Type","application/json"); return header; } @Override public String getBodyContentType() { return "application/json; charset=utf-8"; } @Override public byte[] getBody() throws AuthFailureError { try { return mRequestBody == null ? null : mRequestBody.getBytes("utf-8"); } catch (UnsupportedEncodingException uee) { VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8"); return null; } } }; queue.add(stringRequest); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(LoginActivity.this, "参数构建失败", Toast.LENGTH_SHORT).show(); } } }); } }
关键改动说明:
- 将
StringRequest的创建逻辑完全移到login_btn的点击事件内部,确保每次点击时都能获取用户最新的输入内容 - 把
RequestQueue的初始化留在onCreate里,避免重复创建队列 - 给
HashMap加上泛型声明HashMap<String, String>,避免编译器警告 - 在
JSONException的捕获分支增加了提示Toast,方便调试
内容的提问来源于stack exchange,提问作者chamara nishantha
相关产品推荐
相关产品推荐

