Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Volley attach access token to evey request using singleton

I am doing the following which perfectly works

    //else proceed with the checks
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
            Request.Method.GET,
            checkauthurl,
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(String response) { 
                         //do stuff here
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                   // do stuff here
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String> ();
                    TokenService tokenservice = new TokenService(ctx);
                    String accesstoken = tokenservice.getToken(ApiHelper.ACCESS_TOKEN_SHARED_PREF);
                    headers.put("Authorization", "Bearer " + accesstoken);

                    return headers;
              }
    };

    // Access the RequestQueue through your singleton class.
    ApiSingleton strngle = new ApiSingleton(ctx);
    strngle.addToRequestQueue(jsonObjectRequest);

For every request, I have to add the request header. How can I set request headers directly in the singleton.

This is my singleton

private static ApiSingleton mInstance;
private RequestQueue mRequestQueue;
public static Context mCtx;
private ImageLoader mImageLoader;

public ApiSingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();
    //do stuff
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

How do I avoid the above code duplication when attaching the bearer token in every request?

like image 465
Geoff Avatar asked Mar 14 '18 17:03

Geoff


1 Answers

public class CustomJsonRequest extends JsonRequest<Object>{
    public CustomJsonRequest(String url, String requestBody, Response.Listener<Object> listener,
                       Response.ErrorListener errorListener) {
        super(url, requestBody, listener, errorListener);
    }

    public CustomJsonRequest(int method, String url, String requestBody, Response.Listener<Object> listener,
                       Response.ErrorListener errorListener) {
        super(method, url, errorListener);
    }
    @Override
    protected Response<Object> parseNetworkResponse(NetworkResponse response) {
        return Response.success(Object, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<String, String> ();
        TokenService tokenservice = new TokenService(ctx);
        String accesstoken = tokenservice.getToken(ApiHelper.ACCESS_TOKEN_SHARED_PREF);
        headers.put("Authorization", "Bearer " + accesstoken);
        return headers;
    }
}

You can extend JsonRequest class and override getHeaders() method. Pass instance of CustomJsonRequest object when you are adding volley requests in queue.

VolleyUtils.getInstance().addToRequestQueue(customJsonRequest); 
like image 96
abhishesh Avatar answered Sep 28 '22 07:09

abhishesh