HTTPURLConnection
启用基于doc 但使用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
一样工作的问题。