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);

client.setParams(params);

HttpGet get = new HttpGet(url);

String credentials = getCredentials();

if(credentials!=null){

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

ResponseHandler responseHandler=new BasicResponseHandler();

try {

result = client.execute(get, responseHandler);

} catch (ClientProtocolException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

}

}

return result;

}

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

[Via http://josnidhin.wordpress.com]

No comments:

Post a Comment