Java – How do I disable checking for the WWW-Authenticate header on 401 in HttpUrlConnection on Android?

How do I disable checking for the WWW-Authenticate header on 401 in HttpUrlConnection on Android?… here is a solution to the problem.

How do I disable checking for the WWW-Authenticate header on 401 in HttpUrlConnection on Android?

The web service I’m using returns a 401 when my authentication cookie expires, which causes HttpUrlConnection to throw this error:

java.io.IOException: No authentication challenges found
    at libcore.net.http.HttpURLConnectionImpl.getAuthorizationCredentials(HttpURLConnectionImpl.java:427)
    at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:407)
    at libcore.net.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:356)
    at ...

I know this happens because the server doesn’t return the WWW-Authenticate header, but that’s beyond my control. Glad HttpUrlConnection did this check for me, but this is the real world and we are not always able to use servers that fully follow the HTTP specification. I can’t get rid of HttpUrlConnection due to other code dependencies, so how do I disable checking so I can actually use the response?

Solution

You can try catch the error.

try{
     code that causes error
}
catch(IOException ex){
    if(ex.getMessage().equals("No authentication challenges found")){
        handle error
    }
}

Related Problems and Solutions