Bohemian Bohemian - 1 year ago 106
Android Question

How to do HTTP authentication in android?

I am checking out the class org.apache.http.auth.
Any more reference or example if anyone has?

Answer Source

I've not met that particular package before, but it says it's for client-side HTTP authentication, which I've been able to do on Android using the APIs, like so:

Authenticator.setDefault(new Authenticator(){
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("myuser","mypass".toCharArray());
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();

Obviously your getPasswordAuthentication() should probably do something more intelligent than returning a constant.

If you're trying to make a request with a body (e.g. POST) with authentication, beware of Android issue 4326. I've linked a suggested fix to the platform there, but there's a simple workaround if you only want Basic auth: don't bother with Authenticator, and instead do this:

c.setRequestProperty("Authorization", "basic " +
        Base64.encode("myuser:mypass".getBytes(), Base64.NO_WRAP));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download