[英]Android 4.3 HTTPUrlConnection + Basic Auth - No authentication challenges found
I am using Basic Authentication on a HttpURLConnection to fetch some data. 我在HttpURLConnection上使用基本身份验证来获取一些数据。 Up until 4.2 this worked just fine, but with 4.3 on the Nexus 4 I get a java.io.IOException: No authentication challenges found when querying the response code. 直到4.2,这工作得很好,但在Nexus 4上有4.3,我得到一个java.io.IOException:查询响应代码时没有发现身份验证挑战 。 The strange thing is that the problem does not occur when I run the same code on a 4.3 emulator. 奇怪的是,当我在4.3模拟器上运行相同的代码时,问题不会发生。
I tried the solution mentioned here, but no luck: HTTP Basic Authentication issue on Android Jelly Bean 4.1 using HttpURLConnection 我尝试了这里提到的解决方案,但没有运气: 使用HttpURLConnection在Android Jelly Bean 4.1上的HTTP基本身份验证问题
Code: 码:
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();
Trace: 跟踪:
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来解决该问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.