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?

12/28/2009 7:39:28 AM

Accepted Answer

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));
11/15/2016 1:27:06 PM

For me, it worked,

final String basicAuth = "Basic " + Base64.encodeToString("user:password".getBytes(), Base64.NO_WRAP);

Apache HttpCLient:

request.setHeader("Authorization", basicAuth);


connection.setRequestProperty ("Authorization", basicAuth);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow