我在Android应用中使用HttpClient
4.1,并试图让我的应用的API请求被其中一个“您需要登录或支付wifi”屏幕拦截的智能设备变得聪明。检测并处理需要登录的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;
}
});
然后在我的活动:
try {
response = httpClient.get(url);
} catch (WifiLoginNeeded e){
showWifiLoginScreen();
}
,其中显示的wifi屏幕做到这一点:
Uri uri = Uri.parse("http://our-site.com/wifi-login");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
的思考是这样的:
- 我的API绝不会合法地重定向
- 所以我配置的HttpClient把我的特殊的RuntimeException当它重定向
- 捕获了异常的活动代码,并弹出一个网页视图,让他们直接登录屏幕
- 一旦他们登录,wifi登录祝贺他们做得好,并提示他们回到应用程序
事情是,我从来没有得到该WifiLoginNeeded异常。使用Android完成此操作的首选方法是什么?
首先,确保你的http服务器返回正确的httpReponse(301或302)。 – yorkw 2012-03-27 02:48:19
事情是,这不是我的服务器做重定向。这是WiFi接入点之一,它将所有内容指向他们的“登录到我们昂贵的WiFi”页面。所以我需要抓住每个我们可以想到的重定向HTTP调用的情况。 – 2012-03-27 13:46:25
它甚至可能不是您所期望的重定向类型 - 也请确保您所期望的代码正在生成。接入点不必返回您期望的特定HTTP代码,它可能会愉快地发送一个[200]指示您在接入点登录屏幕时一切正常。 您可能希望存储您的站点的IP地址,并将其与最新的http请求返回的IP地址进行比较。如果它们不同,请调出登录屏幕。 – RightHandedMonkey 2012-08-29 23:41:18