Skip to content
This repository has been archived by the owner on Feb 26, 2023. It is now read-only.

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 = "http://some.server.com/services", interceptors = MyAuthInterceptor.class)
public interface RestClient {
    @Get("/events")
    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 {

    @Bean
    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());
        headers.setAuthorization(auth);
        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:

@EActivity
public class MyActivity extends Activity {

    @RestService
    RestClient client;

    @Bean
    MyAuthInterceptor authInterceptor;

    @AfterInject 
    void initAuth() {
        RestTemplate template = client.getRestTemplate();
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(authInterceptor);
        template.setInterceptors(interceptors);
    }
}

Using AndroidAnnotations

Questions?

Enjoying AndroidAnnotations

Improving AndroidAnnotations

Extending AndroidAnnotations

Clone this wiki locally