简体   繁体   中英

Automatically connect to internet when network is available

I have to develop an application which collects some data(from databases or flat files or something else) and connect to a server which is a repository and store the data in it.
The functional requirement is:

  • client application must detect available network
  • connect to network automatically
  • ask user for authentication ... for eg: internet

Any one please suggest me what API I should use.
Is it possible using java?

I would just assume you are connected to the internet and try to connect anyway. If it fails, wait a bit and try again. ad nauseum.

ie You don't need to know if the internet is available to try and use it.

To answer the "internet availability" issue I'd suggest you use apache HttpClient and simply try fetching content from a known URL, eg www.google.com or even a URL related to the specific task of yours. If it succeeds then you know that you've got internet connectivity.

Make sure you use a low connect timeout in order to not completelly block the application in case connectivity is not there.

If you don't use HttpClient but plain Java then set the timeout using the cryptic:

System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); // 10 seconds connect timeout
System.setProperty("sun.net.client.defaultReadTimeout", "60000");    // 60 seconds read timeout

10 seconds to determine whether you have connection or not should be enough. Otherwise it could block forever.

The best way to know the network, or any other resource, is available is to try to use it. You can't actually foretell the future ;-) Just try to make the connection you need to make, and handle the failures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM