我使用isReachable,但它不起作用,我使用了ConnectivityManager和getNetworkInfo;实际上这仅用于检查我是否已连接到互联网...
但问题是我想检查一下我是否可以访问互联网,所以我想ping网站以检查是否有回复。
答案 0 :(得分: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...
}
}
答案 1 :(得分: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");
}
答案 2 :(得分:1)