-
Notifications
You must be signed in to change notification settings - Fork 0
Authenticated Rest Client
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
AndroidAnnotations was created by Pierre-Yves Ricau and is sponsored by eBusinessInformations.
09/11/2014 The 3.2 release is out !
- Get started!
- Download
- Cookbook, full of recipes
- Customize annotation processing
- List of all available annotations
- Release Notes
- Examples
- Read the FAQ
- Join the Mailing list
- Create an issue
- Tag on Stack Overflow