HTTP Basic Authentication issue on Android Jelly Bean 4.1 using HttpURLConnection

妖精的绣舞 提交于 2019-11-28 12:23:37

We were able to solve Jelly Bean not calling getPasswordAuthentication() of the Authenticator via the following new method:

@TargetApi(Build.VERSION_CODES.FROYO) 
private void setJellyBeanAuth(HttpURLConnection httpConn) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        byte[] auth = (USER + ":" + PASSWORD).getBytes();
        String basic = Base64.encodeToString(auth, Base64.NO_WRAP);
        httpConn.setRequestProperty("Authorization", "Basic " + basic);
    }
}

Then just call this function after opening the connection:

httpURLConn = (HttpURLConnection) url.openConnection();
setJellyBeanAuth(httpURLConn);

The @TargetApi for Froyo annotation is only necessary since we are still supporting API 7 while Base64 was added in API 8

For a 401 UNAUTHORIZED response with Android's httpURLConnection your server must send back a authenticate header like this...
WWW-Authenticate: Bogus realm="blahblah", comment="use form to log in"
as per
http://tools.ietf.org/html/rfc2616 search "10.4.2 401 Unauthorized"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!