How to send Authorization header in Android using Volley library?
Asked Answered
A

6

27

How can I send Authorization header using Volley library in Android for GET method?

This is my request code:

JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url,
            null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d("Response", response.toString());
            pd.dismiss();
            
            Toast.makeText(MainActivity.this, "" + response.toString(), Toast.LENGTH_SHORT).show();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("Error", "Error: " + error.getMessage());
            Toast.makeText(MainActivity.this, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
            pd.dismiss();

        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization", "2e96e0a4ff05ba86dc8f778ac49a8dc0");
            return headers;
        }
    };
Arc answered 16/5, 2017 at 11:27 Comment(3)
You already are sending your authorization header using Map<T,T> getHeaders().Christology
What error do you get?Ashcraft
i got this Error: com.android.volley.ServerErroArc
S
40
StringRequest request = new StringRequest(Request.Method.POST, YourUrl, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        if (!response.equals(null)) {
            Log.e("Your Array Response", response);                    
        } else {
            Log.e("Your Array Response", "Data Null");
        }
    }

}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("error is ", "" + error);
    }
}) {    

 //This is for Headers If You Needed
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("Content-Type", "application/json; charset=UTF-8");
        params.put("token", ACCESS_TOKEN);
        return params;
    }

 //Pass Your Parameters here
    @Override
    protected Map<String, String> getParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("User", UserName);
        params.put("Pass", PassWord);
        return params;
    }
};
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
Strepitous answered 18/5, 2017 at 13:37 Comment(1)
When I use TLS(Https) encryption serverside and send the token as Authorization Header like ("Authorization: Basic xyzToken"), is the token transmitted in encrypted form?Higbee
U
13

Try following code:

@Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        String credentials = "username" + ":" + "password";
        String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Basic " + base64EncodedCredentials);
        return headers;
    }
Uruguay answered 16/5, 2017 at 12:1 Comment(3)
public void onErrorResponse(VolleyError error) ----it gives error nullArc
Did you replaced "username" and "password" string with your auth variables?Uruguay
again same public void onErrorResponse(VolleyError error) ----it gives error nulArc
S
3

This can be simply achieved by using the getHeaders() thus;

@Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headerMap = new HashMap<String, String>();
                headerMap.put("Content-Type", "application/json");
                headerMap.put("Authorization", "Bearer " + ACCESS_TOKEN);
                return headerMap;
            }
Stipulate answered 3/9, 2019 at 9:20 Comment(0)
L
2

1.Try using getBodyContentType()::

     JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url,
        null, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {
        Log.d("Response", response.toString());
        pd.dismiss();

        Toast.makeText(MainActivity.this, "" + response.toString(), Toast.LENGTH_SHORT).show();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.d("Error", "Error: " + error.getMessage());
        Toast.makeText(MainActivity.this, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
        pd.dismiss();

    }
}) 
{
     @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "2e96e0a4ff05ba86dc8f778ac49a8dc0");
        return headers;
    }
};
Laryngotomy answered 23/5, 2017 at 5:47 Comment(0)
B
0

If an API needs a Authorization Header then Using Volley we need to do this :

JsonObjectRequest jsonObejct = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            Log.wtf("The Response ",response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Authorization", "XXXX");
            return params;
        }
      };
Barth answered 8/7, 2018 at 17:4 Comment(0)
I
0

try this code

 @Override
public Map<String, String> getHeaders() throws AuthFailureError {
    String credentials = preferenceHelper.getEmail() + ":" + preferenceHelper.getPassword();
    String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT);
    HashMap<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Basic " + base64EncodedCredentials);
    return headers;
}
Indivertible answered 4/1, 2019 at 9:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.