如何从Android活动ping网站并获得响应?

Amt*_*t87 3 connection android ping

我使用isReachable,但它不起作用,我使用了ConnectivityManager和getNetworkInfo; 实际上这只是为了检查我是否连接到互联网...

但问题是我想检查我是否可以访问互联网,所以我想ping网站以检查是否有回复.

Mah*_*raa 6

对于get方法:

private void executeReq(URL urlObject) throws IOException{
    HttpURLConnection conn = null;

    conn = (HttpURLConnection) urlObject.openConnection();
    conn.setReadTimeout(100000); //Milliseconds
    conn.setConnectTimeout(150000); //Milliseconds
    conn.setRequestMethod("GET");
    conn.setDoInput(true);

    // Start connect
    conn.connect();
    String response = convertStreamToString(conn.getInputStream());
    Log.d("Response:", response);
}
Run Code Online (Sandbox Code Playgroud)

你可以用它来打电话

try {
    String parameters = ""; //
    URL url = new URL("http://alefon.com" + parameters);
    executeReq(url);
}
catch(Exception e){
    //Error
}
Run Code Online (Sandbox Code Playgroud)

要检查Internet连接,请使用:

private void checkInternetConnection() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (null == ni)
        Toast.makeText(this, "no internet connection", Toast.LENGTH_LONG).show();
    else {
         Toast.makeText(this, "Internet Connect is detected .. check access to sire", Toast.LENGTH_LONG).show();
         //Use the code above...
    }
}
Run Code Online (Sandbox Code Playgroud)