I want to check if a web service is available before connecting to it, so that if it is not available, I can display a dialog that says so. My first attempt is this:
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;
}
And then in a separate class I do
if(...isAvailable()){
HttpPost httpPost = new HttpPost("SAME URL HERE");
StringEntity postEntity = new StringEntity(SOAPRequest, HTTP.UTF_8);
postEntity.setContentType("text/xml");
httpPost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8");
httpPost.setEntity(postEntity);
// Get the response
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httpPost);
// Convert HttpResponse to InputStream for parsing
HttpEntity responseEntity = httpResponse.getEntity();
InputStream soapResponse = responseEntity.getContent();
// Parse the result and do stuff with the data...
}
However I'm connecting to the same URL twice, and this is inefficient and probably slowing down my code.
First of all, is it?
Secondly, what's a better way to do this?