Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set custom header in Volley Request

How can custom headers be set for a Volley request? At the moment, there is way to set body content for a POST request. I've a simple GET request, but I need to pass the custom headers alongwith. I don't see how JsonRequest class supports it. Is it possible at all?

like image 960
bianca Avatar asked Jun 11 '13 16:06

bianca


People also ask

How do I add a header in volley?

If you need to add custom headers to your volley requests, you can't do this after initialisation, as the headers are saved in a private variable. Instead, you need to override the getHeaders() method of Request.

What is Android volley Clienterror?

Indicates that the server responded with an error response indicating that the client has erred. For backwards compatibility, extends ServerError which used to be thrown for all server errors, including 4xx error codes indicating a client error.

How do I make my volley request synchronous?

We are going to make synchronous HTTP Request using volley. To make synchronous HTTP request make a RequestFuture object. And make JsonObjectRequest pass this parameter RequestMethod, URL, pass object of type Json and pass RequestFuture instance.


2 Answers

The accepted answer with getParams() is for setting POST body data, but the question in the title asked how to set HTTP headers like User-Agent. As CommonsWare said, you override getHeaders(). Here's some sample code which sets the User-Agent to 'Nintendo Gameboy' and Accept-Language to 'fr':

public void requestWithSomeHttpHeaders() {     RequestQueue queue = Volley.newRequestQueue(this);     String url = "http://www.somewebsite.com";     StringRequest getRequest = new StringRequest(Request.Method.GET, url,          new Response.Listener<String>()          {             @Override             public void onResponse(String response) {                 // response                 Log.d("Response", response);             }         },          new Response.ErrorListener()          {             @Override             public void onErrorResponse(VolleyError error) {                 // TODO Auto-generated method stub                 Log.d("ERROR","error => "+error.toString());             }         }     ) {              @Override         public Map<String, String> getHeaders() throws AuthFailureError {                  Map<String, String>  params = new HashMap<String, String>();                   params.put("User-Agent", "Nintendo Gameboy");                   params.put("Accept-Language", "fr");                  return params;           }     };     queue.add(getRequest);  } 
like image 52
georgiecasey Avatar answered Nov 16 '22 00:11

georgiecasey


It looks like you override public Map<String, String> getHeaders(), defined in Request, to return your desired HTTP headers.

like image 26
CommonsWare Avatar answered Nov 15 '22 22:11

CommonsWare