Android,HttpURLConnection和处理错误的凭据

我正在执行GET请求:

HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
urlConnection.setReadTimeout(READ_TIMEOUT);
urlConnection.connect();

到那时,凭证已经设置为:

Authenticator.setDefault(new Authenticator() {
  protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(loginNameString, passwordString.toCharArray());
  }
});

当我提供良好的凭证(即用户名和密码)时,一切正常.

提供错误凭据时连接会发生什么变化?例如,如果我故意提供错误的凭据,并且在urlConnection.connect()之后立即调用urlConnection.getResponseCode()我的应用程序最终会超时并且我必须强制关闭.这是为什么?

**编辑.据我所知,当凭证不好时,HttpURLConnection只是继续尝试连接(即使有限超时). (我知道这是因为我在返回之前添加了行Log.v(“Authentication”,“Calling …”);在我的getPasswordAuthentication()方法中).如果连接失败,我希望连接停止尝试!

解决方法:

使用Basic auth,解决方法是:

connection.setRequestProperty("Authorization", "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.DEFAULT));

使用android.util.Base64包.另请注意,自API 8(Android 2.2)起,encodeToString()方法才可用.

此外,http://code.google.com/p/android/issues/detail?id=7058是相关的.

上一篇:java – Android:如何使用HttpsURLConnection以编程方式登录网页


下一篇:中断HttpURLConnection请求Android