0

I am using below code and Volley lib to call api. in this just passing method and url , I need to pass headers also.

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
            "http//xyz", null, new Response.Listener<JSONObject>()
  • 2
    you override getHeaders() http://stackoverflow.com/questions/17049473/how-to-set-custom-header-in-volley-request – sivaBE35 Feb 22 '17 at 12:23

2 Answers2

2

Like this:

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, new JSONObject(), new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            //Handle response here
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //Handle errors here
        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("HEADER KEY", "HEADER VALUE");
            return params;
        }
    };
    requestQueue.add(jsonObjectRequest);
MichaelStoddart
  • 5,571
  • 4
  • 27
  • 49
1

You have to override getHeaders() for putting header information. Follow this -

 private void callToApi(){

 String serverUrl = serverUrl+"&lat="+99.9999+"&lng="+76.9887;

        JsonObjectRequest weatherUpdateRequest = new JsonObjectRequest
                (Request.Method.GET, serverUrl, null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(CLASS_NAME, " JSON: " + response.toString());


                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO Auto-generated method stub

                    }
                }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "Bearer ghbgrbhrgt");

                return headers;

            }

        };

        Volley.newRequestQueue(getApplicationContext()).add(weatherUpdateRequest);
    }
AGM Tazim
  • 2,213
  • 3
  • 16
  • 25