【问题标题】:Android HttpUrlConnection doesn't support digest authentication?Android HttpUrlConnection 不支持摘要认证?
【发布时间】:2014-06-25 15:36:08
【问题描述】:
  • 我想使用HTTPURLConnection来启用基于doc的android支持的缓存
  • 但是当使用 HTTPURLConnection 时返回 401 responseCode

        String BASIC_AUTH = "Basic "
            + Base64.encodeToString((USER+":"+PASS).getBytes(),
                    Base64.NO_WRAP);
    HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
    
    con.setConnectTimeout(CONNECT_TIMEOUT);
    con.setReadTimeout(READ_TIMEOUT);
    con.setRequestProperty("Authorization", BASIC_AUTH);
    // Enable cache
    con.setUseCaches(true);
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Accept", "*/*");
    // add reuqest header
    con.setRequestMethod("GET");
    int responseCode = con.getResponseCode();
    Log.d("Response Code : ", responseCode + ""); // return 401
    
  • 使用 apache 时 DefaultHttpClient 完美运行

        DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(null, -1),
            new UsernamePasswordCredentials(USER,PASS));
    
    HttpResponse httpResponse;
    HttpEntity httpEntity;
    String url = apiURL.getURL();
    // request method is GET
    String paramString = URLEncodedUtils.format(params, "utf-8");
    url += "?" + paramString;
    HttpGet httpGet = new HttpGet(url);
    httpGet.setHeader("Accept", "text/json");
    httpResponse = httpClient.execute(httpGet);
    httpEntity = httpResponse.getEntity();
    
  • 如何在HTTPURLConnecion 上设置Credentials 以像apache DefaultHttpClient 一样工作的问题。

【问题讨论】:

    标签: java android caching httpclient httpurlconnection


    【解决方案1】:

    设置凭据的默认机制是使用Authenticator.setDefault,但它仅适用于基本身份验证。

    Android 上的HttpUrlConnection 尚不支持摘要,因此您必须自己实现RFC2617

    请在此处查看我的answer,了解如何执行此操作的摘要。

    【讨论】:

      【解决方案2】:

      试试不带空格的"user:pass"

      【讨论】:

      • @KhaledLela 嗯,让它与你想要的第二个代码 sn-p USER+":"+PASS 非常相似。我用 http://httpbin.org/basic-auth/user/pass 尝试了你的固定代码 sn-p(删除了空格),它对我来说很好。
      • @HansKratz digest 身份验证的问题,我认为可以使用 basic authentication
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-24
      相关资源
      最近更新 更多