Adding parameters on Restful API using JsonObjectRequest on Android Studio

1.3k Views Asked by At

I'm calling a restful api on my android project and I used Volley and JsonObjectRequest, I thought that the third parameter of the JsonObjectRequest which is jsonRequest are the api parameters so I created a json object for that which in the end I only got errors. So is it common to directly add the api parameters on the url? instead of passing it on a json object? what is the third parameter for, it would be really helpful if someone can give me an example. And my last question is how do you get the entire json response instead of using response.getString("title") for each key.

//api parameters directly added on the url
String URL = "https://www.myapi.com/?param=sample&param1=sample1";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL, null,
            new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    String title = response.getString("Title");
                    Log.d("title", title);
                } catch(Exception e){
                    Log.e("response error", e.toString());
                }

            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, error.toString());
            }
        });
1

There are 1 best solutions below

5
Michael Dougan On

Below your Response.ErrorListener() you need to add these two overrides:

new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(TAG, error.toString());
    }) {
    @Override
    protected Map<String, String> getParams() 
    {  
            Map<String, String>  params = new HashMap<String, String>();  
            params.put("param", "sample");
            params.put("param1", "sample1);

            return params;  
    }

   @Override
   public Map<String, String> getHeaders() throws AuthFailureError {
       HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Accept", "application/x-www-form-urlencoded; charset=UTF-8");
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
       return headers;
   }
};