Authenticated Rest Client

Csaba Kozák edited this page May 4, 2015 · 7 revisions

Since AndroidAnnotations 2.2

AndroidAnnotations @Rest annotation generates an implementation that uses Spring Android Rest Template.

Please start by reading the Rest API documentation.

Spring Android Rest Template already provides everything we need for request authentication, so let's use it!

Let's say we have the following rest client:

@Rest(rootUrl = "", interceptors = MyAuthInterceptor.class)
public interface RestClient {
    EventList getEvents();

and a bean that stores authentication information:

@EBean(scope = Scope.Singleton)
public class MyAuthStore {
    public String getUsername() {
      return "H2G2";

    public String getPassword() {
      return "42";

We create a ClientHttpRequestInterceptor that will intercept every request:

@EBean(scope = Scope.Singleton)
public class MyAuthInterceptor implements ClientHttpRequestInterceptor {

    MyAuthStore authStore;

    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();
        HttpAuthentication auth = new HttpBasicAuthentication(authStore.getUsername(), authStore.getPassword());
        return execution.execute(request, body);

Before AndroidAnnotations 3.1

It was not possible to inject an [@EBean](Enhance custom classes) ClientHttpRequestInterceptor interceptor object to the RestTemplate via the interceptors parameter, so you had to do it manually:

public class MyActivity extends Activity {

    RestClient client;

    MyAuthInterceptor authInterceptor;

    void initAuth() {
        RestTemplate template = client.getRestTemplate();
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();

14/10/2018 The 4.5.1 release is out !

Using AndroidAnnotations


Enjoying AndroidAnnotations

Improving AndroidAnnotations

Extending AndroidAnnotations

Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.