我在 HttpURLConnection 上使用基本身份验证来获取一些数据。直到 4.2 这工作得很好,但是在 Nexus 4 上使用 4.3 我得到一个java.io.IOException: No authentication challenge found when querying the response code。奇怪的是,当我在 4.3 模拟器上运行相同的代码时,并没有出现问题。
我尝试了这里提到的解决方案,但没有运气:Android Jelly Bean 4.1 上的 HTTP Basic Authentication issue using HttpURLConnection
代码:
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(2000000);
String userpass = user + ":" + pass;
String basicAuth;
//fix from SO
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
basicAuth = "Basic " + new String(Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP));
}
else {
//Base64: http://iharder.net/base64
basicAuth = "Basic " + new String(com.foo.bar.Base64.encodeBytes(userpass.getBytes()));
}
urlConnection.setRequestProperty ("Authorization", basicAuth);
//throws Exception
urlConnection.getResponseCode();
痕迹:
09-01 21:40:13.501: W/System.err(23055): java.io.IOException: No authentication challenges found
09-01 21:40:13.501: W/System.err(23055): at libcore.net.http.HttpURLConnectionImpl.getAuthorizationCredentials(HttpURLConnectionImpl.java:438)
09-01 21:40:13.501: W/System.err(23055): at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:418)
09-01 21:40:13.501: W/System.err(23055): at libcore.net.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:367)
09-01 21:40:13.501: W/System.err(23055): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:301)
09-01 21:40:13.501: W/System.err(23055): at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:497)
09-01 21:40:13.501: W/System.err(23055): at com.foo.bar.InputStreamHelper.getUrlConnectionFromUrl(InputStreamHelper.java:65)