Tuesday, 11 October 2011

Android: how to make a RESTful GET request using Http basic authentication

Let's assume we're sending a request to the url https://mytargetdomain.com/verify to verify a certain username and password combination, and we'll get a 200 status code on success. The code for this is as follows:

DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(
 new AuthScope(null, -1),
 new UsernamePasswordCredentials("myusername", "mypassword"));
HttpGet httpGet = new HttpGet("https://mytargetdomain.com/verify");
try
{
 HttpResponse response = httpClient.execute(httpGet);
 StatusLine statusLine = response.getStatusLine();
 int statusCode = statusLine.getStatusCode();
 if (statusCode == 200) { /* authorisation successful, do something... */ }
 else { /* authorisation failed, do something... */ }
}
catch (Exception ex) { /* Exception caught, do something... */ }
httpClient.getConnectionManager().shutdown();

Of course, this is a non-asynchronous call, which is not recommended, but hopefully this post serves the purpose of showing how to make a RESTful GET request using Http basic authentication.

No comments: