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();
 new AuthScope(null, -1),
 new UsernamePasswordCredentials("myusername", "mypassword"));
HttpGet httpGet = new HttpGet("https://mytargetdomain.com/verify");
 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... */ }

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: