Get Response header when 401 occurred

点点圈 提交于 2019-12-11 19:40:03

问题


Hi I am working on android and java.So my problem is that whenever 401 occurred I am not able to get response header and also not able to get status code. I am using http url connection. My code looks like this:

String https_url = "http://abc.com";
      HttpsURLConnection con = null;
      int status;
      URL url;
      try {

         url = new URL(https_url);
         con = (HttpsURLConnection)url.openConnection();

         con.setDoInput(true);
         int responseCode = con.getResponseCode();   //throw IOException:Received authentication challenge is null
        if (responseCode == 200)
        {

        }
        else
        {

        }
      } catch (MalformedURLException e) {
         e.printStackTrace();
      } catch (IOException e) {
          Log.i("&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*", "inside exception");
          if (con != null) {
              Log.i("&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*", "inside not null");
          int responseCodeAfterException = con.getResponseCode();
          Log.i("&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*", "inside not null and response");
          Log.i("&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*", "inside not null and response"+responseCodeAfterException);
          // Handle according to new response code
      }
         e.printStackTrace();
      }

I am not getting any field from response header. I know this is authentication problem and my server giving 401 in response but I am not able to get that response code. Am I doing anything wrong. How to handle this kind of exception. Need Help Thank you.


回答1:


Take a look at this question: IOException: Received authentication challenge is null.

It seems that the exception is thrown because the response doesn't include a WWW-Authenticate header (See the spec). I can't be sure this is your case, however you can check it, and maybe, if that's the case and you are in control of the server party, can try to fix the server code to return the header.

Otherwise, you can only catch the IOException and report it to your application.



来源:https://stackoverflow.com/questions/19066369/get-response-header-when-401-occurred

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!