【问题标题】:HttpURLConnection authentication modeHttpURLConnection 认证方式
【发布时间】:2016-12-07 09:15:52
【问题描述】:

我正在使用 HttpURLConnection 类来管理我的 Android 应用程序中的 HTTP 连接。问题是,在某些服务器上,我有一个代码 401 使用在 Internet 导航器上工作的 URL。我使用基本身份验证初始化连接,但我认为这些服务器需要其他模式。我知道它适用于 libCURL 和以下指令:

curl_easy_setopt(pCurlHandle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

但是有没有办法在 Android 上做类似的事情?目前,我这样做:

...
connection.setRequestProperty("Authorization", "Basic " +  Base64.encode("username:password"));
...

我也试过Authenticator

Authenticator.setDefault(new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication("username", "password".toCharArray());
    }
});

但我的应用中仍有 401。有什么想法吗?

【问题讨论】:

    标签: java httpurlconnection http-authentication


    【解决方案1】:

    嗯,this post 真的帮了我很多忙(但我根本不使用Authenticator 类),现在我的代码完成了这样的工作(如果需要身份验证):

    • 使用基本身份验证初始化我的HttpURLConnection对象(请参阅我的问题代码中的第一个Java示例)

    • 测试我是否收到代码 401,如果是,请检查服务器是否排除在 Digest 身份验证分析响应标头中。

    • 使用手动构建的 Digest 请求属性重试(参见我提到的帖子)

    • 而且有效!

    我希望这个答案会对某人有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-01
      • 2017-12-22
      • 1970-01-01
      • 2018-01-26
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      相关资源
      最近更新 更多