Advertisement
Guest User

Volley Authentication Request

a guest
Aug 27th, 2016
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1.  
  2. import android.util.Base64;
  3.  
  4. import com.android.volley.AuthFailureError;
  5. import com.android.volley.Response;
  6. import com.android.volley.toolbox.StringRequest;
  7.  
  8. import java.util.HashMap;
  9. import java.util.Map;
  10.  
  11. /**
  12.  * Created by Glenn on 8/25/2016.
  13.  */
  14. public class AuthStringRequest extends StringRequest {
  15.  
  16.     private String username, password, token;
  17.  
  18.     public AuthStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
  19.         super(method, url, listener, errorListener);
  20.     }
  21.  
  22.     public AuthStringRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
  23.         super(url, listener, errorListener);
  24.     }
  25.  
  26.     public void prepareHeader(String username, String password) {
  27.         this.username = username;
  28.         this.password = password;
  29.     }
  30.  
  31.     public void prepareHeader(String token) {
  32.         this.token = token;
  33.     }
  34.  
  35.     @Override
  36.     public Map<String, String> getHeaders() throws AuthFailureError {
  37.         Map<String, String> headers = new HashMap<String, String>();
  38.         String credentials, auth;
  39.         if(token.isEmpty()) {
  40.             credentials = username + ":" + password;
  41.             auth = "Basic "
  42.                     + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
  43.         } else {
  44.             credentials = token;
  45.             auth = "Bearer "
  46.                     + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
  47.         }
  48.         headers.put("Content-Type", "application/json");
  49.         headers.put("Authorization", auth);
  50.         return headers;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement