我有以下代码来检查服务器可用性,但它不起作用 我使用连接管理器检查互联网可用性它运作良好
public static boolean isConnected(Context context, String url){
ConnectivityManager connectivityManager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager!=null){
if ((connectivityManager.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)
||(connectivityManager.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING)
||(connectivityManager.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING)
||(connectivityManager.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED))
{
try{
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(5000);
connection.connect();
return true;
} catch (Exception e) {
// Handle your exceptions
return false;
}
}
}
return false;
}
答案 0 :(得分:2)
有很多方法。但我选择这种方式。你可以像下面这样实施:
HttpClient httpclient = new DefaultHttpClient();
String response = null;
URI url;
try {
String s = "url";
url = new URI(s.replace(" ", "%20"));
Log.e("my webservice", "My webservice : " + url);
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = null;
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);
// Execute HTTP Post Request
httpResponse = httpClient.execute(httpget);
response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
Log.e("Login service", "resonse length : " + url);
if(response.length()>0){
return true;//server available
}else{
return false;//server not available
}
// this is what we extended for the getting the response string
// which we going to parese for out use in database //
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return false;
答案 1 :(得分:1)
你可以这样做:
HttpParams httpParams = new BasicHttpParams();
//int some_reasonable_timeout = (int) (30 * DateUtils.SECOND_IN_MILLIS);
int some_reasonable_timeout = 10;
HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout);
HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout);
//DefaultHttpClient client = new DefaultHttpClient();
// get the response
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StatusLine status = response.getStatusLine();
Log.d("tag","status is"+status.toString());
if (status.getStatusCode() == HttpStatus.SC_OK)
{
//cserver is available
}
else
{
//server is not available
}
答案 2 :(得分:0)
您可以简单地声明Socket
。我在我的许多项目中使用以下代码,超时肯定有效。
Socket socket;
final String host = "your.server.IP.or.host";
final int port = 80;
final int timeout = 30000; // 30 seconds
try {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), timeout);
}
catch (UnknownHostException uhe) {
Log.e("ServerSock", "I couldn't resolve the host you've provided!");
}
catch (SocketTimeoutException ste) {
Log.e("ServerSock", "After a reasonable amount of time, I'm not able to connect, Server is probably down!");
}
catch (IOException ioe) {
Log.e("ServerSock", "Hmmm... Sudden disconnection, probably you should start again!");
}
但是,这可能很棘手。正好在UnknownHostException
s,可能需要更长时间才能超时,大约45秒 - 但另一方面,这通常发生在你无法解析主机时,这更像是意味着你的互联网访问错误配置了DNS解析(这是不可能的)。
无论如何,如果你想对冲你的赌注,你可以简单地使用你的IP地址而不是主机。这样,如果您的任何例外情况发生,您将确保这不是问题。