使用 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中文網其他相關文章!