SK9*_*SK9 4 android httpurlconnection
我正在执行GET请求:
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
urlConnection.setReadTimeout(READ_TIMEOUT);
urlConnection.connect();
Run Code Online (Sandbox Code Playgroud)
到那时,凭证已经设置为:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(loginNameString, passwordString.toCharArray());
}
});
Run Code Online (Sandbox Code Playgroud)
当我提供良好的凭证(即用户名和密码)时,一切正常.
提供错误凭据时连接会发生什么变化?例如,如果我故意提供错误的凭据,并且urlConnection.getResponseCode()在urlConnection.connect()我的应用程序最终超时之后我立即打电话,我必须强制关闭.这是为什么?
**编辑.据我所知,当凭证不好时,HttpURLConnection只是继续尝试连接(即使有限超时).(我知道这是因为我在返回之前Log.v("Authentication", "Calling...");在我的getPasswordAuthentication()方法中添加了这一行).如果连接失败,我希望连接停止尝试!
使用Basic auth,解决方法是:
connection.setRequestProperty("Authorization", "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.DEFAULT));
Run Code Online (Sandbox Code Playgroud)
使用android.util.Base64包.另请注意,该encodeToString()方法自API 8(Android 2.2)开始提供.
此外,http://code.google.com/p/android/issues/detail?id = 7058也很重要.
| 归档时间: |
|
| 查看次数: |
2649 次 |
| 最近记录: |