Android:检查与服务器的连接

Fly*_*ynn 5 android android-service

所以我有一种方法可以检查设备是否基于此连接到互联网

它工作正常,但在一些情况下,我发现尽管手机显示连接到互联网,它仍然无法访问我的服务器.我真正想做的是检查与我的特定URL的连接.

我怎么能实现呢?

aho*_*der 25

你可以这样做:

public boolean isConnectedToServer(String url, int timeout) {
    try{
        URL myUrl = new URL(url);
        URLConnection connection = myUrl.openConnection();
        connection.setConnectTimeout(timeout);
        connection.connect();
        return true;
    } catch (Exception e) {
        // Handle your exceptions
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

这将尝试连接到您的服务器的URL,如果失败,您显然没有连接.;-)