Android 4.3 HTTPUrlConnection + Basic Auth - 未发现身份验证质询

时间:2013-09-02 09:48:06

标签: java android httpurlconnection basic-authentication android-4.3-jelly-bean

我在HttpURLConnection上使用基本身份验证来获取一些数据。直到4.2,这工作得很好,但在Nexus 4上有4.3,我得到一个 java.io.IOException:查询响应代码时没有发现身份验证挑战。奇怪的是,当我在4.3模拟器上运行相同的代码时,问题不会发生。

我尝试了这里提到的解决方案,但没有运气:HTTP Basic Authentication issue on Android Jelly Bean 4.1 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)

1 个答案:

答案 0 :(得分:0)

通过将构建目标提升到API级别18来解决问题