1
  • I want to use HTTPURLConnection to enable cache which is supported on android based on doc
  • But when using HTTPURLConnection return 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
    
  • When using apache DefaultHttpClient work perfect.

        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();
    
  • The question how to set Credentials on HTTPURLConnecion to work like apache DefaultHttpClient.

Khaled Lela
  • 7,831
  • 6
  • 45
  • 73

2 Answers2

0

The default mechanism to set the credentials is using Authenticator.setDefault, but it will only work for basic authentication.

HttpUrlConnection on Android does not support digest yet, you therefore have to implement RFC2617 by yourself.

See my answer here for a summary on how to do that.

Community
  • 1
  • 1
Nappy
  • 3,016
  • 27
  • 39
-2

Try "user:pass" without the spaces.

HHK
  • 4,852
  • 1
  • 23
  • 40
  • @KhaledLela Hmm, to make it really similar to the second code snippet you want `USER+":"+PASS`. I tried your fixed code snippet (spaces removed) with http ://httpbin.org/basic-auth/user/pass and it works fine for me. – HHK Jun 25 '14 at 17:09
  • @HansKratz The problem with `digest` authentication , I think that work with `basic authentication`. – Khaled Lela Jun 28 '14 at 07:20