Month: September 2013

Volley HTTP library for Android with BasicAuth

Volley is an incredibly useful library for Android. It alleviates almost all of the headaches of asynchronous web service calls. Here’s a video of the Google I/O session on Volley that I was lucky enough to attend.

Use git to clone volley from here if you don’t have it already: https://android.googlesource.com/platform/frameworks/volley

I don’t want to go into the intro to Volley, there are tons of those blog posts out there already.

For my latest app that I’m working on, I had to extend it a small bit to get BasicAuth working so I thought I would share an example.

It’s pretty straightforward to get BasicAuth working. You just have to extend the type of request that you want to use. In my case, I had to extend JSONArrayRequest and JSONObjectRequest. Here’s the array extension class as an example. The object version is the same extension, just add the basic auth header in the constructor of the request class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.myapp.services;
 
import java.util.HashMap;
import java.util.Map;
 
import org.json.JSONArray;
 
import android.util.Base64;
 
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonArrayRequest;
 
public class MyArrayRequest extends JsonArrayRequest{
 
	public MyArrayRequest(String url, JSONArray jsonRequest,
			Listener<JSONArray> listener, ErrorListener errorListener) {
		super(url, listener, errorListener);
	}
 
	public MyArrayRequest(String url, Response.Listener<JSONArray> listener,
						Response.ErrorListener errorListener, String username, String password) {
		super(url, listener, errorListener);
		if (username != null && password != null) {
			String loginEncoded = new String(Base64.encode((username + ":" + password).getBytes(), Base64.NO_WRAP));
			this.headers.put("Authorization", "Basic " + loginEncoded);
		}
	}
 
	private Map<String, String> headers = new HashMap<String, String>();
		@Override
		public Map<String, String> getHeaders() throws AuthFailureError {
			return headers;
	}
 
	public void setHeader(String title, String content) {
		headers.put(title, content);
	}
}