当web服务不可用时,我需要处理一个异常。在我的应用程序中,我正在请求一个web服务,它将返回一个xml数据。Web服务可用时,我的应用程序工作正常。但当web服务不可用时,我的应用程序就会崩溃。如何在java中捕获该异常。请注意,我正在开发一个Android应用程序。
当Web服务不可用时,它看起来像下图
最佳答案
有了这个,你可以检查webservice是否可用
public void isAvailable(){
// first check if there is a WiFi/data connection available... then:
URL url = new URL("URL HERE");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Connection", "close");
connection.setConnectTimeout(10000); // Timeout 10 seconds
connection.connect();
// If the web service is available
if (connection.getResponseCode() == 200) {
return true;
}
else return false;
}