HttpsURLConnection在Android中没有返回401

时间:2012-07-30 14:59:36

标签: java android android-4.0-ice-cream-sandwich http-status-code-401 httpsurlconnection

我遇到了一个似乎很奇怪的问题。我正在Android应用程序中使用HttpsURLConnection类,并使用Authenticator类进行身份验证。

我可以使用输入的用户名和密码连接到Web服务,然后获取JSON响应。如果我输入有效的凭据,这工作绝对正常,我得到返回的响应。但是,如果我给它无效的凭据然后我永远不会得到响应,我的异步任务(运行代码)永远不会完成。

进行连接的代码如下:

private static String retrieveStream(String url) throws SocketTimeoutException {

    String streamContent = "";
    HttpsURLConnection urlConnection = null;

    try {

        Log.d("Connection", "Connecting to: " + url);

        Log.d("Connection", "Opening connection");
        urlConnection = (HttpsURLConnection) new URL(url).openConnection();
        Log.d("Connection", "Setting connect timeout");
        urlConnection.setConnectTimeout(5000);
        Log.d("Connection", "Setting read timeout");
        urlConnection.setReadTimeout(5000);
        Log.d("Connection", "Setting Allow All certs (because this is just testing)");
        urlConnection.setHostnameVerifier(new AllowAllHostnameVerifier());

        Log.d("Connection", "Connection Response: " + urlConnection.getResponseCode() + " " + urlConnection.getResponseMessage());

        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            streamContent = readStreamFromConnection(urlConnection);
            Log.d("Connection", "Returned content is: " + streamContent);
        }

    } catch (MalformedURLException e) {
        Log.e("Error", "MalformedURLException thrown in retrieveStream: " + e);
    } catch (IOException e) {
        Log.e("Error", "IOException thrown in retrieveStream for " + url + " : " + e);
    } finally {
        urlConnection.disconnect();
    }

    return streamContent;
}

如果我使用无效凭据运行此操作,这就是我在日志中获得的内容:

07-30 15:52:57.040: DEBUG/Connection(16000): Connecting to: https://webservice-that-i-use
07-30 15:52:57.040: DEBUG/Connection(16000): Opening connection
07-30 15:52:57.040: DEBUG/Connection(16000): Setting connect timeout
07-30 15:52:57.040: DEBUG/Connection(16000): Setting read timeout
07-30 15:52:57.040: DEBUG/Connection(16000): Setting Allow All certs (because this is just testing)

然后它就会挂起,直到我强制停止应用程序或重新部署。我没有任何例外或ANR。

我似乎遇到与发布here完全相同的问题,但它从未得到过回答。有没有人知道为什么会这样?如何通过HttpsURLConnection在无效凭证上获得超时连接?

任何帮助将不胜感激。我还应该注意到,我的同事在iOS中工作正常,所以这不是服务器问题。这是在Asus Transformer TF101上运行的ICS SDK。

感谢阅读!

0 个答案:

没有答案