2012-03-26 63 views
3

我用isReachable,但它沒有工作,我用ConnectivityManager和getNetworkInfo;其實這僅適用於檢查,如果我連接到互聯網...如何從Android活動ping一個網站並得到迴應?

但問題是我要檢查,所以我想用ping一個網站,以檢查是否有響應,我可以訪問互聯網。

回答

5

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 
} 

調用它來檢查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... 
    } 
} 
+0

謝謝@Mohammed,問題是,我要檢查,如果我可以訪問任何網站,如果是讓舉杯說:「有上網」 ......如果不是敬酒說「瀏覽問題」,即使該設備連接到WiFi – Amt87 2012-03-26 14:47:13

+0

我更新答案..檢查它的PLZ ..但它仍然需要檢查訪問網站..因爲可能服務器停機,或沒有訪問等。所以檢查互聯網連接,然後檢查呼叫站點和得到迴應.... – 2012-03-26 15:09:32

3

使用這一個.. 該作品對我來說很好:)

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"); 
} 
相關問題