我在一款Android应用程序中使用HttpClient
4.1,并尝试让它能够智能地处理我的应用程序API请求被那些“您需要登录或支付WiFi费用”的屏幕拦截的情况。
我想弹出一个Webview,允许用户进行登录。
我一直在尝试在httpClient中拦截重定向,但是我没有成功。
这是我目前正在尝试的:
this.client = new DefaultHttpClient(connectionManager, params);
((DefaultHttpClient) this.client).setRedirectStrategy(new DefaultRedirectStrategy() {
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
boolean isRedirect = Boolean.FALSE;
try {
isRedirect = super.isRedirected(request, response, context);
} catch (ProtocolException e) {
Log.e(TAG, "Failed to run isRedirected", e);
}
if (!isRedirect) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 301 || responseCode == 302) {
throw new WifiLoginNeeded();
// The "real implementation" should return true here..
}
} else {
throw new WifiLoginNeeded();
}
return isRedirect;
}
});
然后在我的Activity中:
try {
response = httpClient.get(url);
} catch (WifiLoginNeeded e){
showWifiLoginScreen();
}
展示无线网络屏幕的位置:
Uri uri = Uri.parse("http://our-site.com/wifi-login");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
思路如下:
- 我的 API 永远不会合法重定向
- 所以我配置了 HttpClient,在它被重定向时抛出我的特殊 RuntimeException
- 在 activity 代码中捕获该异常并弹出 Webview,将它们引导到登录屏幕
- 一旦他们登录,wifi-login 就会祝贺他们做得很好,并提示他们返回应用程序
问题是,我从未收到那个 WifiLoginNeeded 异常。使用 Android,有哪种首选的方法来完成这个目标?