Simple HTTPS - PerfectCarl/androidannotations GitHub Wiki
Since AndroidAnnotations 2.6
@HttpsClient
The @HttpsClient
simplifies HTTPS requests by injecting a HttpClient
instance with a configured KeyStore, TrustStore and Hostname Verification.
All parameters are optionals.
Usage examples
Mutual SSL authentication (two-way authentication)
Here is the complete form if you want to achieve Client Auth:
@HttpsClient(trustStore=R.raw.cacerts,
trustStorePwd="changeit",
keyStore=R.raw.client,
keyStorePwd="secret",
allowAllHostnames=false)
HttpClient httpsClient;
-
trustStore: int, Resource id of your trust store file ex
R.raw.cacerts.bks
Typically your servers trusted certificates (public key, Root Chain Authority etc) -
trustStorePwd: String, Your TrustStore password (default is changeit)
-
keyStore: int, Resource id of your keystore Usually your private key (client certificate)
-
keyStorePwd: Your KeyStore password (default is changeit)
-
allowAllHostnames: boolean, if true, authorizes any TLS/SSL hostname (default
true
) If false, Hostname in certificate (DN) must match the URL
Note: Prior to ICS, Android accept [Key|Trust]store only in BKS format (Bouncycastle Key Store)
A simple SSL authentication
This is useful if your remote server use a selfsigned certificate or a certificate issued by a private certificate authority
@HttpsClient(trustStore=R.raw.mycacerts,
trustStorePwd="changeit")
HttpClient httpsClient;
Default
If you do not specify a truststore file, the annotation will use the default android truststore located at /system/etc/security/cacerts.bks
which allows you to connect to a server signed with one of the trusted root CAs (Thawte, verisign etc.)
@HttpsClient
HttpClient httpsClient;
Complete Example
@EActivity
public class MyActivity extends Activity {
@HttpsClient(trustStore=R.raw.cacerts,
trustStorePwd="changeit",
hostnameVerif=true)
HttpClient httpsClient;
@AfterInject
@Background
public void securedRequest() {
try {
HttpGet httpget = new HttpGet("https://www.verisign.com/");
HttpResponse response = httpsClient.execute(httpget);
doSomethingWithResponse(response);
} catch (Exception e) {
e.printStackTrace();
}
}
@UiThread
public void doSomethingWithResponse(HttpResponse resp) {
Toast.makeText(this, "HTTP status " + resp.getStatusLine().getStatusCode(), Toast.LENGTH_LONG).show();
}
}