Android关于连接需要Portal认证的WIFI

前言

有时候会遇到个很蛋疼的问题,访问网络时候代码的逻辑时若果当前网络连接就访问,否则就不访问。这时候如果不想在具体的代码逻辑中添加一些判断的话,遇到手机连接到需要认证登陆的wifi的情况就吃屎了。

这种需要登陆的wifi一般就是在我们发任何一个HTTP请求时候重定向到它的登录界面。这时候我想知道我是不是连接到了这样的wifi该怎么呢?其实Google提供了关于HttpURLConnection在这种情况下的判断,思路很简单就是判断请求后url的Host和请求前是否相同,代码如下

 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     if (!url.getHost().equals(urlConnection.getURL().getHost())) {
       // we were redirected! Kick the user out to the browser to sign on?

     ...
   } finally {
     urlConnection.disconnect();
   }
 }

那么对于HttpClient要怎么做呢?

 public static String get(String url) throws IOException{
        String content = null;
        HttpResponse response = null;
        HttpGet get = new HttpGet(url);
        get.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");
        HttpConnectionParams.setConnectionTimeout(get.getParams(), 5000);
        HttpContext httpContext=new BasicHttpContext();
        response = httpClient.execute(get,httpContext);
        HttpHost currentHost = (HttpHost) httpContext
                .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (!currentHost.getHostName().equals(get.getURI().getHost())){
        //这时候就应该是连接着需要登录的wifi
        }
        HttpEntity entity = response.getEntity();
        content = EntityUtils.toString(entity);
        return content;
    }

你可能感兴趣的:(Android)