检测并处理需要登录的wifi

Mat*_*uno 17 android httpclient wifi

HttpClient在一个Android应用程序中使用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;
    }
});
Run Code Online (Sandbox Code Playgroud)

然后在我的活动中:

try {
    response = httpClient.get(url);
} catch (WifiLoginNeeded e){
    showWifiLoginScreen();
}
Run Code Online (Sandbox Code Playgroud)

show wifi屏幕执行此操作:

Uri uri = Uri.parse("http://our-site.com/wifi-login");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

思路是这样的:

  • 我的API永远不会合法重定向
  • 因此,我将HttpClient配置为在重定向时抛出特殊的RuntimeException
  • 在活动代码中捕获该异常并弹出Webview以将它们定向到登录屏幕
  • 一旦他们登录,wifi-login就会祝贺他们做得好,并提示他们回到应用程序

问题是,我从来没有得到WifiLoginNeeded异常.使用Android实现此目的的首选方法是什么?

Pav*_*oid -2

请检查下面的代码。检查您正在使用的连接类型可能对您有用。

WifiManager lWifiManager = (WifiManager) OpenYouTubePlayerActivity.this.getSystemService(Context.WIFI_SERVICE);
TelephonyManager lTelephonyManager = (TelephonyManager) OpenYouTubePlayerActivity.this.getSystemService(Context.TELEPHONY_SERVICE);

////////////////////////////
// if we have a fast connection (wifi or 3g)
if( (lWifiManager.isWifiEnabled() && lWifiManager.getConnectionInfo() != null && lWifiManager.getConnectionInfo().getIpAddress() != 0) ||
    ( (lTelephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS ||

    /* icky... using literals to make backwards compatible with 1.5 and 1.6 */      
    lTelephonyManager.getNetworkType() == 9 /*HSUPA*/  ||
    lTelephonyManager.getNetworkType() == 10 /*HSPA*/  ||
    lTelephonyManager.getNetworkType() == 8 /*HSDPA*/  ||
    lTelephonyManager.getNetworkType() == 5 /*EVDO_0*/  ||
    lTelephonyManager.getNetworkType() == 6 /*EVDO A*/) 

    && lTelephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED) 
    ){
        //Do some thing here
}
Run Code Online (Sandbox Code Playgroud)