安卓:检查连接到服务器 [英] Android: Check connection to server

查看:178
本文介绍了安卓:检查连接到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有检查,如果该设备基于这一个连接到互联网的方法

So I have a method that checks if the device is connected to the internet based on this one

它的工作原理确定,但在几个案例我发现,虽然手机显示正在连接到互联网,它仍然无法访问我的服务器。什么我真的希望去做检查连接到我的具体URL。

It works ok, but in a couple of cases I find that although the phone shows being connected to the internet, it still does not have access to my server. What I am really looking to do it check connection to my specific URL.

我怎么能实现呢?

推荐答案

您可以这样做:

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;
    }
}

这将尝试连接到服务器的URL,如果失败,你显然不具备的连接。 ; - )

This will attempt to connect to your server's URL and if it fails, you obviously don't have a connection. ;-)

这篇关于安卓:检查连接到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆