前言
有時候會遇到個很蛋疼的問題,通路網絡時候代碼的邏輯時若果目前網絡連接配接就通路,否則就不通路。這時候如果不想在具體的代碼邏輯中添加一些判斷的話,遇到手機連接配接到需要認證登陸的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(), );
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;
}