使用在Android果冻豆4.1 HTTP基本身份验证问题的HttpURLConnection [英] HTTP Basic Authentication issue on Android Jelly Bean 4.1 using HttpURLConnection

本文介绍了使用在Android果冻豆4.1 HTTP基本身份验证问题的HttpURLConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在HttpURLConnection的基础要求使用HTTP基本身份验证的Web服务器。 code的伟大工程,在Android版本2.x,3.x中,4.0.x的现在与果冻豆和v4.1.x验证失败,在LogCat中以下消息:

We are making HttpURLConnection based request to the Web server using HTTP Basic Authentication. Code works great on Android versions 2.x, 3.x., 4.0.x Now with Jelly Bean and v4.1.x authentication fails with the following messages in the LogCat:

01-27 10:54:18.886: ...::doReadRawData(731): An exception occured while reading data from remote host. httpURLConn.responseCode = 401 / httpURLConn.responseMessage = UNAUTHORIZED
01-27 10:54:18.886: ...::doReadRawData(731): java.io.IOException: No authentication challenges found

我们使用的HttpURLConnection的身份验证code作为Android的文档:

The Authentication code we using for HttpURLConnection as in the Android documentation:

private void doAuthorize() {
        Authenticator.setDefault(new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USER, PASSWORD.toCharArray());
            }
        });
    }

经进一步调查和故障排除,我们发现这个code不被称为4.1果冻豆!

什么解决方法或适当的方式在Android的果冻豆4.1基本验证?

What are the workarounds or proper ways for basic authentication in Android Jelly Bean 4.1?

在本相关主题发现有人在Android源$ C ​​$ C不同,我觉得我们有问题涉及到这种差异:<一href="http://stackoverflow.com/questions/11810447/httpurlconnection-worked-fine-in-android-2-x-but-not-in-4-1-no-authentication-c">HttpURLConnection在安卓2.X而不是在4.1的罚款:未找到

Someone found different in the Android source code in this related topic, I think issue we having is related to that difference: HttpURLConnection worked fine in Android 2.x but NOT in 4.1: No authentication challenges found

推荐答案

我们能够解决果冻豆不通过以下新方法调用验证方的getPasswordAut​​hentication():

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

在@TargetApi为Froyo的注解是唯一必要的,因为我们仍然支持API 7时的Base64中添加了API 8

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

这篇关于使用在Android果冻豆4.1 HTTP基本身份验证问题的HttpURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆