Friday, November 8, 2019

java - Android 4.3 HTTPUrlConnection + Basic Auth - No authentication challenges found

I am using Basic Authentication on a HttpURLConnection to fetch some data. 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. The strange thing is that the problem does not occur when I run the same code on a 4.3 emulator.




I tried the solution mentioned here, but no luck: HTTP Basic Authentication issue on Android Jelly Bean 4.1 using HttpURLConnection



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)

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...