Android HttpUrlConnection不支持摘要式身份验证吗?

时间:2014-06-25 15:36:08

标签: java android caching httpclient httpurlconnection

  • 我想使用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();
    
  • 如何将Credentials HTTPURLConnecion设置为像apache DefaultHttpClient一样工作的问题。

2 个答案:

答案 0 :(得分:0)

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

Android上的

HttpUrlConnection还不支持摘要,因此您必须自己实施RFC2617

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

答案 1 :(得分:-2)

在没有空格的情况下尝试"user:pass"