简体   繁体   中英

Google Volley POST request in android studio with JSON body?

This is my piece of code that I am using to make a POST request.

RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

            String url = "myUrl.....";
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url, response -> {
                Toast.makeText(MainActivity.this, "Response: "+response, Toast.LENGTH_SHORT).show();
                try {
                    JSONObject mainObject = new JSONObject(response);
                    error = mainObject.getBoolean("error");
                    //Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if(!error){
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(userNameShared, email);
                    editor.putString(passwordShared, password);
                    editor.commit();
                    startActivity(new Intent(MainActivity.this, MainActivityDashboard.class));
                }
                else{
                    editTextEmail.setError("Invalid e-mail");
                    editTextPassword.setError("Invalid password");
                    return;
                }

            }, error -> Toast.makeText(MainActivity.this, "Error: "+error.getMessage(), Toast.LENGTH_SHORT).show()){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError
                {
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("email", email);
                    params.put("password", password);
                    params.put("rememberPassword", false);
                    params.put("ip_address", ipAddress);
                    params.put("isCaptchaEnabled", false);
                    return params;
                }

                @Override
                public Map<String,String> getHeaders() throws AuthFailureError {
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("Context-Type","application/json");
                    return params;
                }
            };

            requestQueue.add(stringRequest);
        });

Everything worked perfectly in previous projects but here the problem is now that I want to include boolean values along with String values in the POST body.

The body is as follows: { "email":"username@mail.com", "password":"somepassword", "rememberPassword": false, "ip_address": "152.57.31.41", "isCaptchaEnabled": false }

I am new to API calls and JSON. I tried searching for answers on google but everyone is just using Map<String, String> in getParams wherein in my case I am not sure what must I use. I tried to include the body into JSONObject and tried returning it but it's giving me typecast error. Or is there any other method beside getParams in volley that allows to pass different datatypes in value. Please help me how can I reconfigure my code and make it work.

The answer is fairly simple. We can just use JsonObjectRequest and pass the parameters into it. Here's my working code, just incase anyone faces the same naïve problem.

String postUrl = "yourURL.....";
            RequestQueue requestQueue = Volley.newRequestQueue(this);

            JSONObject postData = new JSONObject();
            try {
                postData.put("email", editTextEmail.getText().toString());
                postData.put("password", editTextPassword.getText().toString());
                postData.put("rememberPassword", false);
                postData.put("ip_address", "1.41");
                postData.put("isCaptchaEnabled", false);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, postUrl, postData, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Toast.makeText(getApplicationContext(), "Response: "+response, Toast.LENGTH_LONG).show();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            });

            requestQueue.add(jsonObjectRequest);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM