java.io.IOException: Received authentication challenge is null in ICS 4.0.3

前端 未结 3 671
走了就别回头了
走了就别回头了 2020-12-06 07:25

I\'m trying to logoff from the server. But it returns \"0\" response code with this exception. I\'m using GET verb to do this.

LogCat

10-17 14         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 08:27

    This error happens beause the server sends a 401 (Unauthorized) but does not give a "WWW-Authenticate" which is a hint for the client what to do next. The "WWW-Authenticate" Header tells the client which kind of authentication is needed (either Basic or Digest). This is usually not very useful in headless http clients, but thats how the standard is defined. The error occurs because the lib tries to parse the "WWW-Authenticate" header but can't.

    Possible solutions if you can change the server:

    • Add a fake "WWW-Authenticate" header like: WWW-Authenticate: Basic realm="fake". This is a mere workaround not a solution, but it should work and the http client is satisfied.
    • Use HTTP status code 403 instead of 401. It's semantic is not the same and usually when working with login 401 is a correct response (see here for detailed discussion) but its close enough.

    Possible solutions if you can't change the server:

    As @ErikZ wrote in his post you could use a try&catch

    HttpURLConnection connection = ...;
    try {
        // Will throw IOException if server responds with 401.
        connection.getResponseCode(); 
    } catch (IOException e) {
        // Will return 401, because now connection has the correct internal state.
        int responsecode = connection.getResponseCode(); 
    }
    

    I also posted this here: java.io.IOException : No authentication challenges found

提交回复
热议问题