我在HttpURLConnection上使用基本身份验证来获取一些数据。在4.2之前,这一切都很好,但在Nexus 4上使用4.3时,我得到了一个java.io.IOException:在查询响应代码时没有发现身份验证挑战。奇怪的是,当我在4.3模拟器上运行相同的代码时,问题并没有发生。
我尝试了这里提到的解决方案,但没有成功:使用HttpURLConnection 的Android Jelly Bean 4.1上的HTTP基本身份验证问题
代码:
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)
通过将构建目标提高到API 18级解决了问题