【发布时间】: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以像apacheDefaultHttpClient一样工作的问题。
【问题讨论】:
标签: java android caching httpclient httpurlconnection