【发布时间】:2014-08-28 06:15:57
【问题描述】:
我的应用需要检查我成功实施的互联网访问。 但我有一个条件是互联网可用,但它试图打开的网站目前已关闭。 在这种情况下,我需要显示不同的消息作为输出。 我该怎么做?请给点意见。
【问题讨论】:
标签: android exception webserver
我的应用需要检查我成功实施的互联网访问。 但我有一个条件是互联网可用,但它试图打开的网站目前已关闭。 在这种情况下,我需要显示不同的消息作为输出。 我该怎么做?请给点意见。
【问题讨论】:
标签: android exception webserver
public boolean isServerReachable()
// To check if server is reachable
{
try {
InetAddress.getByName("google.com").isReachable(3000); //Replace with your name
return true;
} catch (Exception e) {
return false;
}
}
【讨论】:
您应该像这样检查网站响应的状态:
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
并检查 here 以查找您的状态代码。
然后你可以通过检查状态码来完成你的工作:
if (status == 200) // sucess
{
我还建议您使用AsyncTask 进行连接,以便在后台与服务器进行通信。
【讨论】:
尝试捕捉 NoHttpResponseException 如下
try{
//code to try to connect to your server
}catch(NoHttpResponseException ex){
//print stacktrace or display some message to say server is down
}
【讨论】:
你可以使用这个类。制作对象并调用方法。
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context context){
this.context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
public boolean isURLReachable() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL(serverConnection.url); // Insert Url
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(10 * 1000); // 10 s.
urlc.connect();
if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http connection is fine).
Log.wtf("Connection", "Success !");
return true;
} else {
return false;
}
} catch (MalformedURLException e1) {
return false;
} catch (IOException e) {
return false;
}
}
return false;
}
}
【讨论】: