- 我想使用
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
以像 apacheDefaultHttpClient
一样工作的问题。
最佳答案
设置凭据的默认机制是使用Authenticator.setDefault
,但它仅适用于基本身份验证。
HttpUrlConnection
尚不支持摘要,因此您必须实现 RFC2617靠你自己。
查看我的answer这里有关于如何做到这一点的摘要。
关于java - Android HttpUrlConnection 不支持摘要身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24412974/