Authenticated Rest Client - PerfectCarl/androidannotations GitHub Wiki
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("http://some.server.com/services")
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);
}
}
Then, it's just a matter of manually adding the ClientHttpRequestInterceptor
to the RestTemplate
used by our RestClient
:
@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);
}
}
We agree that manual binding is not perfect, and we may provide better ways in the future