【发布时间】:2012-04-10 00:53:22
【问题描述】:
我用的是isReachable,但是没用,我用的是ConnectivityManager和getNetworkInfo;实际上这只适用于检查我是否连接到互联网......
但问题是我想检查我是否可以访问 Internet,所以我想 ping 一个网站以检查是否有响应。
【问题讨论】:
标签: android connection ping
我用的是isReachable,但是没用,我用的是ConnectivityManager和getNetworkInfo;实际上这只适用于检查我是否连接到互联网......
但问题是我想检查我是否可以访问 Internet,所以我想 ping 一个网站以检查是否有响应。
【问题讨论】:
标签: android connection ping
对于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...
}
}
【讨论】:
使用这个.. 这对我来说很好:)
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");
}
【讨论】:
【讨论】: