3

我想在连接到 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,这效率低下,可能会减慢我的代码速度。

首先,是吗?

其次,有什么更好的方法来做到这一点?

4

3 回答 3

3

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

于 2012-10-16T17:15:27.073 回答
0

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

公共静态无效 setConnectionTimeout(HttpParams 参数,int 超时)

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

公共静态无效 setSoTimeout(HttpParams 参数,int 超时)

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

希望这可以帮助。

于 2012-10-16T17:31:12.763 回答
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);
于 2012-10-16T17:32:24.733 回答