How to get 401 response without handling it using try/catch in android

后端 未结 2 593
野性不改
野性不改 2021-02-05 12:51

I am using HttpUrlConnection to make network requests from my android application. Everything works fine except one thing, 401. Whenever the server returns response

相关标签:
2条回答
  • 2021-02-05 13:31

    IOException is quite a general exception, and you cannot safely assume a 401 status code every time it's thrown.

    If the first time you request the status code it happens to contain a 401, HttpURLConnection will throw an IOException. At this point, the internal status of the connection will have changed, and it will now be able to give you the status code, without any error.

    int status = 0;
    try {
        status = conn.getResponseCode();
    } catch (IOException e) {
        // HttpUrlConnection will throw an IOException if any 4XX
        // response is sent. If we request the status again, this
        // time the internal status will be properly set, and we'll be
        // able to retrieve it.
        status = conn.getResponseCode();
    }
    if (status == 401) {
        // ...
    }
    

    For more details, http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection

    0 讨论(0)
  • 2021-02-05 13:45

    try to use HttpClient

    private void setCredentials(String login, String password) {
        if (login != null && password != null)
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(URL_HOST, 80), new UsernamePasswordCredentials(login, password));
    
    }
    
    
    
    private InputStream execute(String url, String login, String password) {
            setCredentials(login, password);
            HttpGet get = new HttpGet(url);
            try {
                HttpResponse response = httpClient.execute(get);
                int code = response.getStatusLine().getStatusCode();
                if (code == HttpURLConnection.HTTP_OK) {
                    InputStream stream = response.getEntity().getContent();
                    return stream;
                } else {
                    Log.e("TAG", "Wrong response code " + code + " for request " + get.getRequestLine().toString());
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    
    0 讨论(0)
提交回复
热议问题