【问题标题】:How can I use http auth information from a URL in Android?如何在 Android 中使用来自 URL 的 http auth 信息?
【发布时间】:2011-05-12 13:56:02
【问题描述】:

在我的浏览器或 iOS 中,当我尝试获取带有编码的 http 身份验证信息的 URL 内容时

http://myUser:myPassword@www.example.com/secure/area/index.html

它只是工作。我正在从 Web 服务获取 URL,如果我能提供帮助,我想避免尝试解析它们以获取其 HTTP 身份验证信息。有没有办法在 Android 中做类似的事情而不实际解析 URL?或者,最好的方法是什么?

更新: 我发现当我尝试在 Authorization 标头中设置身份验证信息时,我得到一个非常奇怪的 FileNotFoundException。

这是我正在使用的代码:

        URL url = new URL(urlString);
        URLConnection connection;
        String authority = url.getAuthority();
        if (authority.contains("@")) {
            String userPasswordString = authority.split("@")[0];
            url = new URL(urlString.replace(userPasswordString + "@", ""));
            connection = url.openConnection();
            String encoded = new String(Base64.encode(userPasswordString.getBytes(), Base64.DEFAULT), "UTF-8");
            connection.setRequestProperty("Authorization", "Basic " + encoded);
        } else {
            connection = url.openConnection();
        }

        InputStream responseStream = connection.getInputStream();

所有信息似乎都检查过了,我已经验证了 url 是正确的,base64 字符串是正确的,并且文件肯定在服务器上——我用 Firefox 打开它完全没有问题,并且 Firebug 显示据我所知,所有正确的标题都与我发送的内容相匹配。我得到的是以下错误(更改了 url 主机以保护无辜者):

java.io.FileNotFoundException: http://a1b.example.com/grid/uploads/profile/avatar/user1/custom-avatar.jpg
  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1061)

知道这是怎么回事吗?

我研究过使用 HttpClient,但在 Issue 16041 中看到建议我们更喜欢 URLConnection。

【问题讨论】:

    标签: android httpurlconnection http-authentication


    【解决方案1】:

    看起来您的浏览器正在应用一些额外的规则来解析 URL。在 Android 中,您可以使用 HTTP 客户端的身份验证机制(例如 BASIC 和 DIGEST)来执行相同的操作。您选择哪一个取决于您尝试对其进行身份验证的服务器。

    Here is a good page 让您开始。

    【讨论】:

      【解决方案2】:

      不幸的是,在 Android 上,您无法将这种格式的用户信息(用户名/密码)传递给 java.net.URL 或 HttpClient 并让它像在浏览器中一样工作。

      我建议使用 URI(请参阅 http://download.oracle.com/javase/1.5.0/docs/api/index.html?java/net/URI.html)来执行此操作:将您的 URL 传递给接受字符串的 URI 构造函数,然后您可以提取用户信息(使用 getUserInfo())。然后,您可以使用 HttpClient 的授权类(参见 http://developer.android.com/reference/org/apache/http/auth/package-summary.html)或自己构建基本的 auth 标头(http://www.avajava.com/tutorials/lessons/how-do-i-connect-to-a-url-using-basic-authentication.html 给出了一个示例)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-22
        • 1970-01-01
        • 2019-11-26
        • 2023-03-04
        • 1970-01-01
        相关资源
        最近更新 更多