How to use POST request in android Volley library with params and header?
Asked Answered
T

2

5

I am trying to learn Volley library for posting data into webservices. I need to implement user registration form, following is the image of postman with parameters and header... postman screen for post request

now problem is, i am getting below error

com.android.volley.ServerError

this is my code for volley post method.

public void postNewComment(){
    try {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = "http://myurl/api/users";
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("email", "[email protected]");
        jsonBody.put("user_type", "C");
        jsonBody.put("company_id", "0");
        jsonBody.put("status", "A");
        jsonBody.put("password", "123456");

        final String requestBody = jsonBody.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("VOLLEY", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.e("VOLLEY", error.toString());
            }
        }) {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                final Map<String, String> headers = new HashMap<>();
                headers.put("Authorization", "Basic " + "My_auth_key");
                headers.put("Content-Type", "application/json");

                return headers;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String responseString = "";
                if (response != null) {
                    responseString = String.valueOf(response.statusCode);
                    // can get more details such as response.headers
                }
                return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
            }
        };

        requestQueue.add(stringRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

please suggest where am i getting wrong. URL is working correct with postman, also as you can see i need to set 2 headers. I also tried this Url post method with AsyncTask and its working good. Now i need to implement this using volley library. kindly suggest. thank you.

this is my logcat error:

E/Volley: [81910] BasicNetwork.performRequest: Unexpected response code 405 for "Myurl"

Tactual answered 12/9, 2017 at 8:5 Comment(4)
post your full logcat log here. com.android.volley.ServerError it should also give you error number like 400,500Brockman
please check sir @SahilManchandaTactual
Please refer Adding post parameters and headers androidhive.info/2014/05/android-working-with-volley-library-1Zoo
@paragKartpay you are getting 405 which means Method not allowed. however if your postman's image. its working. my guess is your volley request is not getting authenticated. Check your header values. you might be doing something wrong in your headers. and one more thing, you don't need to override parseNetworkResponse method. remove it.Brockman
T
18

**Try this one **

    private void sendWorkPostRequest() {

        try {
            String URL = "";
            JSONObject jsonBody = new JSONObject();

            jsonBody.put("email", "[email protected]");
            jsonBody.put("password", "");
            jsonBody.put("user_type", "");
            jsonBody.put("company_id", "");
            jsonBody.put("status", "");

            JsonObjectRequest jsonOblect = new JsonObjectRequest(Request.Method.POST, URL, jsonBody, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    Toast.makeText(getApplicationContext(), "Response:  " + response.toString(), Toast.LENGTH_SHORT).show();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    onBackPressed();

                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    final Map<String, String> headers = new HashMap<>();
                    headers.put("Authorization", "Basic " + "c2FnYXJAa2FydHBheS5jb206cnMwM2UxQUp5RnQzNkQ5NDBxbjNmUDgzNVE3STAyNzI=");//put your token here
                    return headers;
                }
            };
            VolleyApplication.getInstance().addToRequestQueue(jsonOblect);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();

    }
}
Torchwood answered 14/9, 2017 at 7:11 Comment(1)
This answer saved me. Big tnx!Preamplifier
I
1

I have an alternative answer that works pretty well for Android Volley+ library by dworks and Google: See HERE

Imbrication answered 22/6, 2018 at 20:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.