Search code examples
androidapimodel-view-controllerandroid-volley

How to conect MVC api in android with volley?


I have tried this code but didn't work which is first way :

String api = "address mvc api";


                StringRequest jsonObjRequest = new StringRequest(Request.Method.POST,api,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.e("tahg" , ""+response);
                            }
                        }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("volley", "Error: " + error.getMessage());

                    }
                }) {

                    @Override
                    public String getBodyContentType() {
                        return "application/json";
                    }

                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> parametr = new HashMap<String, String>();
                        parametr.put("parametr1", "parametr1");
                        parametr.put("parametr2", "parametr2");
                        parametr.put("parametr3", "parametr3");

                        return parametr;
                    }

                };
                RequestQueue  requestqueue = Volley.newRequestQueue(getApplicationContext());
                requestqueue.add(jsonObjRequest);

And the second way is this that it didn't work too:

HashMap<String, String> params = new HashMap<String, String>();

                params.put("parametr1", "value1");
                params.put("parametr1", "value2");
                params.put("parametr1", "value3");

                params.put("location2", "0");


                String api = "address api";


                JsonObjectRequest jor = new JsonObjectRequest(Request.Method.POST, api, new JSONObject(params), new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();
                        //do other things with the received JSONObject
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

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


                }
                ;
                //add to the request queue
                RequestQueue  requestqueue = Volley.newRequestQueue(getApplicationContext());
                requestqueue.add(jor);

and I should mentioned that I have tried these content type header with both ways :

 1-"application/json"
 2-"application/json; charset=utf-8"
 3-"application/x-www-form-urlencoded"
 4-"application/x-www-form-urlencoded; charset=utf-8"

unfortunately always got this error:

Volley: [420] BasicNetwork.performRequest: Unexpected response code 400 for

api address is :

http://www.api.manelin.com/api/Insert_Advertising

Solution

  • This was the thing in one of my project that I had faced with several years ago and I just remind it and maybe can help you: I writ this class to upload an image with a MVC API:

    import android.graphics.Bitmap;
    import android.util.Log;
    import com.android.volley.AuthFailureError;
    import com.android.volley.DefaultRetryPolicy;
    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.BasicNetwork;
    import com.android.volley.toolbox.DiskBasedCache;
    import com.android.volley.toolbox.HurlStack;
    import com.android.volley.toolbox.ImageRequest;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.android.volley.toolbox.StringRequest;
    import com.android.volley.toolbox.Volley;
    import org.json.JSONObject;
    import java.util.HashMap;
    import java.util.Map;
    import static ir.hpbyp.app.industapp.utils.G.context;
    
    /**
     * Created by pc_vahid on 3/28/2016.
     */
    
    public class helperVolley {
    
        private JsonListner dataRecivedListener;
        private ImageListener ImageListener;
    
        private Response.ErrorListener volleyErrorListener;
    
        private String url;
    
        private String url_place_title;
    
        /**
         * @param URL
         * @param JsonListner
         */
        public helperVolley(String URL, JsonListner JsonListner) {
            this.url = URL;
            this.dataRecivedListener = JsonListner;
    
        }
    
        public helperVolley(String URL, ImageListener imageListener) {
            this.url = URL;
            this.ImageListener = imageListener;
    
        }
    
    
        public void ApiPostMethode(Map<String, String> JSONDATA) {
            final RequestQueue queue = Volley.newRequestQueue(context);
            final JsonObjectRequest jsonSend = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(JSONDATA),
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.i("test", "data :" + response.toString());
                            dataRecivedListener.dataReciver(response.toString());
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("test", "data error:" + error.toString());
                }
            }
            ) {
                @Override
                public String getPostBodyContentType() {
                    return "application/x-www-form-urlencoded";
                }
    
            };
            jsonSend.setRetryPolicy(new DefaultRetryPolicy(
                    10000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(jsonSend);
        }
    
        static RequestQueue queue;
    
    
        public void ApiGetMethode() {
            queue = Volley.newRequestQueue(context);
            StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.i("test", "data :" + response.toString());
                            dataRecivedListener.dataReciver(response);
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("test", "error :" + error.toString());
    
                }
    
            });
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                    100000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(stringRequest);
    
        }
    
        public static void cancelRequests() {
            queue.cancelAll(new RequestQueue.RequestFilter() {
                @Override
                public boolean apply(Request<?> request) {
                    return true;
                }
            });
        }
    
        public void cancel() {
            if (queue != null) {
                queue.cancelAll(new RequestQueue.RequestFilter() {
                    @Override
                    public boolean apply(Request<?> request) {
                        return true;
                    }
                });
            }
    
        }
    
    
        public void ApiPostMethodeWithError(Map<String, String> JSONDATA, Response.ErrorListener volleyerrorlistener) {
            this.volleyErrorListener = volleyerrorlistener;
            queue = Volley.newRequestQueue(context);
            final JsonObjectRequest jsonSend = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(JSONDATA),
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            dataRecivedListener.dataReciver(response.toString());
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("onTextChanged4", error.toString());
                }
            }
            ) {
                @Override
                public String getPostBodyContentType() {
                    return "application/x-www-form-urlencoded";
                }
    
            };
            queue.add(jsonSend);
        }
    
        public void ApiPostStringRequestWithError(final Map<String, String> JSONDATA, Response.ErrorListener volleyerrorlistener) {
    
            queue = Volley.newRequestQueue(context);
            StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    dataRecivedListener.dataReciver(response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    dataRecivedListener.dataReciver(error.toString());
                }
            }) {
    
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = JSONDATA;
                    return params;
                }
    
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    // Removed this line if you dont need it or Use application/json
                    // params.put("Content-Type", "application/x-www-form-urlencoded");
                    return params;
                }
    
            };
            queue.add(sr);
        }
    
        public void ApiGetMethodeWithError(Response.ErrorListener volleyerrorlistener) {
    
            DiskBasedCache cache = new DiskBasedCache(context.getCacheDir(), 16 * 1024 * 1024);
            queue = new RequestQueue(cache, new BasicNetwork(new HurlStack()));
            queue.start();
            this.volleyErrorListener = volleyerrorlistener;
            queue = Volley.newRequestQueue(context);
            StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.i("test", "data :" + response.toString());
                            dataRecivedListener.dataReciver(response);
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    volleyErrorListener.onErrorResponse(error);
                }
            });
            queue.add(stringRequest);
        }
    
        public void GetMethodeObject(final Response.ErrorListener volleyerrorlistener) {
            DiskBasedCache cache = new DiskBasedCache(context.getCacheDir(), 16 * 1024 * 1024);
            queue = new RequestQueue(cache, new BasicNetwork(new HurlStack()));
            queue.start();
            this.volleyErrorListener = volleyerrorlistener;
            queue = Volley.newRequestQueue(context);
    
                JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
                    url, null, new Response.Listener<JSONObject>() {
    
                @Override
                public void onResponse(JSONObject response) {
                    Log.i("test", "data :" + response.toString());
                    dataRecivedListener.dataReciver(response.toString());
                }
            }, new Response.ErrorListener() {
    
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("test", "ERROR :" + error.toString());
                    volleyerrorlistener.onErrorResponse(error);
    
                }
            });
            queue.add(jsonObjReq);
    
        }
    
    
        /**
         * @ this method get the image from the url
         */
        public void LoadImage() {
            ImageRequest request = new ImageRequest(url,
                    new Response.Listener<Bitmap>() {
                        @Override
                        public void onResponse(Bitmap bitmap) {
                            ImageListener.ImageRecived(bitmap);
                        }
                    }, 0, 0, null,
                    new Response.ErrorListener() {
                        public void onErrorResponse(VolleyError error) {
    
                        }
                    });
    
            queue.add(request);
        }
    
    
        public void ApiPostStringRequestWithToken(final Map<String, String> JSONDATA, Response.ErrorListener volleyerrorlistener) {
    
            queue = Volley.newRequestQueue(context);
            StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    dataRecivedListener.dataReciver(response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    dataRecivedListener.dataReciver(error.toString());
                }
            }) {
    
                @Override
                protected Map<String, String> getParams() {
    
                    return JSONDATA;
                }
    
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("authorization", token);
                    return params;
                }
    
                @Override
                public String getBodyContentType() {
                    return "application/x-www-form-urlencoded";
                }
            };
            queue.add(sr);
        }
    
        public String token = "bearer token"; // you should change this token
    }
    

    And this is the listener i used in the above class :

    public interface JsonListner {
        /**
         * @param JSON_DATA
         */
        void dataReciver(String JSON_DATA);
    
    }
    

    And this is one of sample using helper volley :

     helperVolley helperVolley = new helperVolley("your url", new JsonListner() {
                @Override
                public void dataReciver(String JSON_DATA) {
    
                }
            });
            helperVolley.ApiGetMethode();