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?
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.
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.
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.
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); }
It looks like you override public Map<String, String> getHeaders()
, defined in Request
, to return your desired HTTP headers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With