使用 Java 在 Android 中设置 HTTP 响应超时
检查远程服务器连接状态的能力在许多 Android 应用程序中至关重要。但是,延长连接超时可能会导致严重的延迟。本文探讨如何设置 HTTP 响应的超时,以防止不必要的等待。
考虑以下代码片段来检查连接状态:
private void checkConnectionStatus() { HttpClient httpClient = new DefaultHttpClient(); try { String url = "http://xxx.xxx.xxx.xxx:8000/GaitLink/" + strSessionString + "/ConnectionStatus"; Log.d("phobos", "performing get " + url); HttpGet method = new HttpGet(new URI(url)); HttpResponse response = httpClient.execute(method); if (response != null) { String result = getResponse(response.getEntity()); ... } } }
当服务器关闭进行测试时,执行卡在以下行:
HttpResponse response = httpClient.execute(method);
要解决此问题,可以设置超时来限制等待时间。在下面的示例中,建立了两个超时:
HttpGet httpGet = new HttpGet(url); HttpParams httpParameters = new BasicHttpParams(); // Set the connection timeout in milliseconds until a connection is established. 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); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpResponse response = httpClient.execute(httpGet);
这段代码执行时,如果无法建立连接,3秒后会抛出连接异常,5秒后会抛出socket异常如果没有从服务器收到数据,则为秒。
或者,如果您有现有的 HTTPClient 实例(例如 DefaultHttpClient 或 AndroidHttpClient),您可以使用setParams()函数设置其超时参数:
httpClient.setParams(httpParameters);
以上是如何使用 Java 在 Android 中设置 HTTP 响应超时?的详细内容。更多信息请关注PHP中文网其他相关文章!