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

前端 未结 6 1019
时光说笑
时光说笑 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 09:50

    if you are already using retrofit you can do it by retrofit. just make a ping.html page and send an head request to it using retrofit and make sure your http client is configured like below: (followRedirects(false) part is the most important part)

    private OkHttpClient getCheckInternetOkHttpClient() {
        return new OkHttpClient.Builder()
                .readTimeout(2L, TimeUnit.SECONDS)
                .connectTimeout(2L, TimeUnit.SECONDS)
                .followRedirects(false)
                .build();
    }
    

    then build your retrofit like below:

    private InternetCheckApi getCheckInternetRetrofitApi() {
        return (new Retrofit.Builder())
                .baseUrl("[base url of your ping.html page]")             
                .addConverterFactory(GsonConverterFactory.create(new Gson()))
                .client(getCheckInternetOkHttpClient())
                .build().create(InternetCheckApi.class);
    }
    

    your InternetCheckApi.class would be like:

    public interface InternetCheckApi {
        @Headers({"Content-Typel: application/json"})
        @HEAD("ping.html")
        Call checkInternetConnectivity();
    }
    

    then you can use it like below:

    getCheckInternetOkHttpClient().checkInternetConnectivity().enqueue(new Callback() {
         public void onResponse(Call call, Response response) {
           if(response.code() == 200) {
            //internet is available
           } else {
             //internet is not available
           }
         }
    
         public void onFailure(Call call, Throwable t) {
            //internet is not available
         }
      }
    );
    

    note that your internet check http client must be separate from your main http client.

提交回复
热议问题