Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"

like image 473
parag Kartpay Avatar asked Sep 12 '17 08:09

parag Kartpay


People also ask

How do you send query parameters in GET request with volley?

Just enter your URL (and POST parameters if any) and see what is the response of the server for multiple consecutive requests. If again you get the same response result is most probably cached. In that case you may examine the returned headers to check if there are proxy headers.

Is volley a REST API?

Android Volley and Retrofit are the most used libraries for accessing the REST Web APIs today. In this paper, we will present a comparative study between these two libraries, in order to disclose the advantages and limitations of each of them.


1 Answers

**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();

    }
}
like image 58
Harshal Deshmukh Avatar answered Sep 26 '22 16:09

Harshal Deshmukh