如何检查Web服务是否可用,然后一次连接到它?

时间:2012-10-16 17:14:29

标签: java android web-services soap

我想在连接之前检查一个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两次,这效率很低,可能会减慢我的代码速度。

首先,是吗?

其次,有什么更好的方法呢?

3 个答案:

答案 0 :(得分:3)

我只是尝试连接,如果超时,则处理异常并显示错误。

答案 1 :(得分:0)

可能你应该考虑查看HttpConnectionParams类的方法。

  

public static void setConnectionTimeout(HttpParams params,int   超时)

     

设置超时,直到建立连接。值为零   表示未使用超时。默认值为零。

     

public static void setSoTimeout(HttpParams params,int timeout)

     

设置默认套接字超时(SO_TIMEOUT),以毫秒为单位   等待数据的超时。超时值为零   被解释为无限超时。没有套接字时使用此值   超时在方法参数中设置。

希望这有帮助。

答案 2 :(得分:0)

如上所述,以下是检查时间的方法:

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);

然后将HttpParameters传递给httpClient的构造函数:

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);