- I want to use
HTTPURLConnection
to enable cache which is supported on android based on doc But when using
HTTPURLConnection
return401 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
onHTTPURLConnecion
to work like apacheDefaultHttpClient
.
Asked
Active
Viewed 787 times
1

Khaled Lela
- 7,831
- 6
- 45
- 73
2 Answers
-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