如何通过Java检查是否可以连接到互联网?一种方法是:
final URL url = new URL("http://www.google.com");
final URLConnection conn = url.openConnection();
... if we got here, we should have net ...
但是有没有更适合执行这项任务的东西,特别是如果您需要经常进行连续检查,而且失去互联网连接的可能性非常高?
如何通过Java检查是否可以连接到互联网?一种方法是:
final URL url = new URL("http://www.google.com");
final URLConnection conn = url.openConnection();
... if we got here, we should have net ...
但是有没有更适合执行这项任务的东西,特别是如果您需要经常进行连续检查,而且失去互联网连接的可能性非常高?
public boolean checkInternetConnection()
{
boolean status = false;
Socket sock = new Socket();
InetSocketAddress address = new InetSocketAddress("www.google.com", 80);
try
{
sock.connect(address, 3000);
if(sock.isConnected()) status = true;
}
catch(Exception e)
{
status = false;
}
finally
{
try
{
sock.close();
}
catch(Exception e){}
}
return status;
}
这段代码包含在我用于测试连接是否可用的jUnit测试类中。我总是能够获得连接,但如果您检查内容长度,如果不知道,则应该为-1:
try {
URL url = new URL("http://www.google.com");
URLConnection connection = url.openConnection();
if(connection.getContentLength() == -1){
fail("Failed to verify connection");
}
}
catch (IOException e) {
fail("Failed to open a connection");
e.printStackTrace();
}
现在有针对这个的API,但它们是平台特定的:
在Android上,ConnectivityManager
(https://developer.android.com/training/basics/network-ops/reading-network-state)可以满足你的所有需求。
在Windows上,INetworkListManager::GetConnectivity (你需要一个JNI)。
在通用Linux上,你可能只能测试是否可以访问DNS服务器和Google,如上所述。
很可能还有一个苹果的方法来做这件事情。
(如果有可用的特定工具,我会使用它们)
你可以简单地写成这样
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main {
private static final String HOST = "localhost";
public static void main(String[] args) throws UnknownHostException {
boolean isConnected = !HOST.equals(InetAddress.getLocalHost().getHostAddress().toString());
if (isConnected) System.out.println("Connected");
else System.out.println("Not connected");
}
}
这对我很有效。
try{
InetAddress addr = InetAddress.getByName("google.com" );
}catch(IOException e){
JOptionPane.showMessageDialog(new JFrame(),"No Internet connection.\nTry again later", "Network Error", JOptionPane.ERROR_MESSAGE);
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView mtv=findViewById(R.id.textv);
ConnectivityManager connectivityManager=
(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(((Network)connectivityManager.getActiveNetwork())!=null)
mtv.setText("true");
else
mtv.setText("fasle");
}
}
}
还有一个Gradle选项--offline
,可能会产生您想要的行为。