3

我遇到了一个似乎很奇怪的问题。我在我的 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。

似乎我遇到了与此处发布的完全相同的问题,但从未得到答复。有没有人知道为什么会发生这种情况?如何使用 HttpsURLConnection 使连接超时?

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

谢谢阅读!

4

0 回答 0