How to check for unrestricted Internet access? (captive portal detection)

前端 未结 6 1023
时光说笑
时光说笑 2020-12-04 09:13

I need to reliably detect if a device has full internet access, i.e. that the user is not confined to a captive portal (also called walled garden), i.e. a

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 10:14

    This is best done here as in AOSP : https://github.com/aosp-mirror/platform_frameworks_base/blob/6bebb8418ceecf44d2af40033870f3aabacfe36e/core/java/android/net/captiveportal/CaptivePortalProbeResult.java#L61

    https://github.com/aosp-mirror/platform_frameworks_base/blob/e3a0f42e8e8678f6d90ddf104d485858fbb2e35b/services/core/java/com/android/server/connectivity/NetworkMonitor.java

    private static final String GOOGLE_PING_URL = "http://google.com/generate_204";
    private static final int SOCKET_TIMEOUT_MS = 10000;
    
    public boolean isCaptivePortal () {
    
    try {
                URL url = new URL(GOOGLE_PING_URL);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
                urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
                urlConnection.setUseCaches(false);
                urlConnection.getInputStream();
                return (urlConnection.getResponseCode() != 204)
                        && (urlConnection.getResponseCode() >= 200)
                        && (urlConnection.getResponseCode() <= 399);
            } catch (Exception e) {
                // for any exception throw an exception saying check was unsuccesful
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
    }
    

    Please note this will probably not work on a proxy network and something more advanced as in the AOSP url needs to be done

提交回复
热议问题