Search code examples
javaandroidhttpandroid-volleyandroid-networking

HTTP-Headers not included in request made with Volley


I have the below request but for some reason the headers aren't being "attached" to the request? Please could you maybe assist me with this?

public void get(String servicesUrl, String end_tag_url) {

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url + servicesUrl + end_tag_url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    System.out.println(response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println(error);
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("header1", "value");
            params.put("header2", "value");
            return params;
        }
    };
// Add the request to the RequestQueue.
    queue.add(stringRequest);
}

I get connection to the server but the is an auth failure because the headers aren't being implemented in the connection.

I have tested on a Chrome add-on called Advanced-Rest-Client and added the headers which worked.

I could add 2 of the headers to the URL but the 3rd one cannot be attached to the URL and needs to be a header?


Solution

  • When creating a request, override getHeaders(), like so:

     new JsonObjectRequest(url, jsonRequest, listener, errorListener) {
    
            @Override
            public Map<String, String> getHeaders() {
    
                Map<String, String> map = new HashMap<String, String>();
                map.put("X-REST-API-Key", resources.getString(R.string.parse_api_key));
                map.put("X-Application-id",
                        resources.getString(R.string.application_id));
    
                if (sessionToken != null) {
                    map.put("X-Session-Token", sessionToken);
                }
    
                return map;
            }
        };