为了完整起见,让我发布一些我添加的代码。我认为发出 Http 请求并在请求成功时返回 true 是相当通用的 HttpClient 代码。我使用 HttpHead 是因为我不关心响应中的实体,这应该使它更快。此方法位于名为 ConnectivityHelper 的类中,而 DefaultSettings 是一个定义了一堆有用常量的类。
public static boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo;
try {
netInfo = manager.getActiveNetworkInfo();
} catch (Exception e) {
netInfo = null;
}
return netInfo != null && netInfo.isConnected() && testConnection(DefaultSettings.TEST_CONNECTION_URL);
}
private static boolean testConnection(String url) {
HttpClient httpClient = null;
HttpHead request = null;
HttpResponse response = null;
int statusCode = 0;
try {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, DefaultSettings.CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(myParams, DefaultSettings.SO_TIMEOUT);
httpClient = new DefaultHttpClient(myParams);
request = new HttpHead(url);
response = httpClient.execute(request);
statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200)
{
Log.e(ConnectivityHelper.class.getName(), String.format("testConnection not successful. For %s - Status code = %d", url, statusCode));
return false;
}
return true;
} catch(ClientProtocolException e) {
Log.e(ConnectivityHelper.class.getName(), String.format("testConnection failure. For %s - Exception: %s.", url, e.toString()));
if (request != null && !request.isAborted()) {
request.abort();
}
return false;
} catch(IOException e) {
if (statusCode == 401) {
Log.e(ConnectivityHelper.class.getName(), String.format("testConnection access denied. For %s - Status code = %d", url, statusCode));
} else {
Log.e(ConnectivityHelper.class.getName(), String.format("testConnection failure. For %s - Exception: %s.", url, e.toString()));
}
if (request != null && !request.isAborted()) {
request.abort();
}
return false;
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
}
}