如何在Android活动中ping一个网站并获得响应?

3

我曾经使用isReachable方法,但是它没有生效。后来我使用了ConnectivityManager和getNetworkInfo方法,但实际上这只能检查是否连接到互联网...

我的问题在于,我想要检查是否可以访问互联网,所以我想要ping一个网站来检查是否有响应。

3个回答

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

您可以使用以下方式调用:
try {
    String parameters = ""; //
    URL url = new URL("http://alefon.com" + parameters);
    executeReq(url);
}
catch(Exception e){
    //Error
}

检查互联网连接,请使用:

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

谢谢@Mohammed,问题是我想检查是否可以访问任何网站,如果可以,则让Toast显示“有互联网访问”...如果不能,则Toast显示“浏览问题”,即使设备已连接到wifi。 - Amt87
我更新了答案,请检查一下。但是仍然需要检查网站的访问权限,因为服务器可能会崩溃或无法访问等等。所以请先检查网络连接,然后再调用网站并获取响应。 - Maher Abuthraa

4

使用这个... 这对我来说很好用 :)

public static void isNetworkAvailable(Context context){
    HttpGet httpGet = new HttpGet("http://www.google.com");
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    try{
        Log.e("checking", "Checking network connection...");
        httpClient.execute(httpGet);
        Log.e("checking", "Connection OK");
        return;
    }
    catch(ClientProtocolException e){
        e.printStackTrace();
    }
    catch(IOException e){
        e.printStackTrace();
    }

    Log.e("checking", "Connection unavailable");
}

0

这个答案对我有用。

不要忘记添加互联网权限:

<uses-permission android:name="android.permission.INTERNET" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接