Sunday, January 24, 2010

Http Basic Authentication On Android

The following show how you can do http basic authentication on android.

public static String httpAuthUrl(String url){

String result = null;

DefaultHttpClient client = new DefaultHttpClient();

HttpParams params = new BasicHttpParams();

HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

HttpProtocolParams.setContentCharset(params, “UTF_8″);

HttpProtocolParams.setUseExpectContinue(params, false);


HttpGet get = new HttpGet(url);

String credentials = getCredentials();


get.addHeader(“Authorization”,”Basic “+credentials);

ResponseHandler responseHandler=new BasicResponseHandler();

try {

result = client.execute(get, responseHandler);

} catch (ClientProtocolException e) {


} catch (IOException e) {




return result;


The function getCredentials() return the username/password as a base64 encodes string. Example – return Base64.encodeBytes((username+”:”+password).getBytes()) something like this.


No comments:

Post a Comment