Add custom headers in volley request
Asked Answered
F

4

5

I have a Volley Request code

RequestQueue queue = Volley.newRequestQueue(this);
String url =<My URL>;

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

How do I set a header called Authorization in this??

Fanti answered 10/10, 2015 at 12:31 Comment(0)
B
1

you can write a class extends Request.(override getHeaders() and so on) just like

public abstract class AbsRequest<T> extends Request<T>{

    public AbsRequest(int method, String url, Response.ErrorListener listener) {
        this(method, url, null, listener);
    }

    public AbsRequest(int method, String url, Map<String, String> params, Response.ErrorListener listener) {
        this(method, url, params, null, listener);
    }

    public AbsRequest(int method, String url, Map<String, String> params, Map<String, String> head, Response.ErrorListener listener) {
        this(method, url, params, head, null, listener);
    }

    public AbsRequest(int method, String url, Map<String, String> params, Map<String, String> head, String bodyContentType, Response.ErrorListener listener) {
        this(method, url, params, null, head, bodyContentType, listener);
    }

    public AbsRequest(int method, String url, String body, Map<String, String> head, String bodyContentType, Response.ErrorListener listener) {
        this(method, url, null, body, head, bodyContentType, listener);
    }

    private AbsRequest(int method, String url, Map<String, String> params, String body, Map<String, String> head, String bodyContentType,  Response.ErrorListener listener) {
        super(method, url, listener);
    }
}

for more information you can see https://github.com/Caij/CodeHub/blob/master/lib/src/main/java/com/caij/lib/volley/request/AbsRequest.java how to use can see https://github.com/Caij/CodeHub/tree/master/app/src/main/java/com/caij/codehub/presenter/imp

Bortman answered 10/10, 2015 at 12:49 Comment(0)
F
25

Override getHeaders in request like:

 StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Display the first 500 characters of the response string.
                    mTextView.setText("Response is: "+ response.substring(0,500));
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mTextView.setText("That didn't work!");
        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params =  super.getHeaders();
            if(params==null)params = new HashMap<>();
            params.put("Authorization","Your authorization");
            //..add other headers
            return params;
        }
    };
Fennec answered 10/10, 2015 at 12:40 Comment(1)
If you get VolleyError: java.lang.UnsupportedOperationException, remove Map<String,String> params = super.getHeaders(); if(params==null)params = new HashMap<>(); , and add Map<String, String> params = new HashMap<>(); Refer to this: https://mcmap.net/q/1920599/-unsupportedoperationexception-while-calling-volley-request-with-headersScorify
B
1

you can write a class extends Request.(override getHeaders() and so on) just like

public abstract class AbsRequest<T> extends Request<T>{

    public AbsRequest(int method, String url, Response.ErrorListener listener) {
        this(method, url, null, listener);
    }

    public AbsRequest(int method, String url, Map<String, String> params, Response.ErrorListener listener) {
        this(method, url, params, null, listener);
    }

    public AbsRequest(int method, String url, Map<String, String> params, Map<String, String> head, Response.ErrorListener listener) {
        this(method, url, params, head, null, listener);
    }

    public AbsRequest(int method, String url, Map<String, String> params, Map<String, String> head, String bodyContentType, Response.ErrorListener listener) {
        this(method, url, params, null, head, bodyContentType, listener);
    }

    public AbsRequest(int method, String url, String body, Map<String, String> head, String bodyContentType, Response.ErrorListener listener) {
        this(method, url, null, body, head, bodyContentType, listener);
    }

    private AbsRequest(int method, String url, Map<String, String> params, String body, Map<String, String> head, String bodyContentType,  Response.ErrorListener listener) {
        super(method, url, listener);
    }
}

for more information you can see https://github.com/Caij/CodeHub/blob/master/lib/src/main/java/com/caij/lib/volley/request/AbsRequest.java how to use can see https://github.com/Caij/CodeHub/tree/master/app/src/main/java/com/caij/codehub/presenter/imp

Bortman answered 10/10, 2015 at 12:49 Comment(0)
S
0

A call to super.getHeaders() throws UnSupportedOperationException. remove super.getHeaders() to get rid off that.

Sickroom answered 15/3, 2017 at 12:27 Comment(0)
S
0

This here is a sample volley request showing how to add headers

private void call_api(final String url){

    if(!this.isFinishing() && getApplicationContext() != null){
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                resultsTextView.setVisibility(View.INVISIBLE);
                loader.setVisibility(View.VISIBLE);
            }
        });

        Log.e("APICALL", "\n token: " + url);


        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("APICALL", "\n response: " + response);
                        if(!FinalActivity.this.isFinishing()){
                            try {
                                JSONObject response_json_object = new JSONObject(response);

                                    JSONArray linkupsSuggestionsArray = response_json_object.getJSONObject("data").getJSONArray("package");
                                    final JSONObject k = linkupsSuggestionsArray.getJSONObject(0);
                                    final String result = k.getJSONArray("action").getJSONObject(0).getString("url");
                                    last_results_type = k.getString("type");
                                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                                        @Override
                                        public void run() {

                                            loader.setVisibility(View.INVISIBLE);
                                            resultsTextView.setText(result);
                                            resultsTextView.setVisibility(View.VISIBLE);
                                        }
                                    });
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(), "An unexpected error occurred.", Toast.LENGTH_LONG).show();
                                finish();
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("APICALL", "\n error: " + error.getMessage());
                        Toast.makeText(getApplicationContext(), "Check your internet connection and try again", Toast.LENGTH_LONG).show();
                        finish();
                    }
                }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("apiUser", "user");
                headers.put("apiKey", "key");
                headers.put("Accept", "application/json");
                //headers.put("Contenttype", "application/json");
                return headers;
            }

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<>();
                map.put("location", "10.12 12.32");
                return map;
            }

        };
        stringRequest.setShouldCache(false);
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }
}
Sewell answered 5/5, 2021 at 6:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.