我想在连接到 Web 服务之前检查它是否可用,这样如果它不可用,我可以显示一个这样的对话框。我的第一次尝试是这样的:
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;
}
然后在一个单独的班级我做
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...
}
但是,我两次连接到同一个 URL,这效率低下,可能会减慢我的代码速度。
首先,是吗?
其次,有什么更好的方法来做到这一点?