為了檢查網絡連接的情況,我創建了下邊的方法:
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);
有人知道怎麼設置超時來避免等待太長的時間嗎?
謝謝!
在我的示例中有兩個超時的設置。連接超時聲明拋出異常"java.net.SocketTimeoutException: Socket is not connected",Socket超時是"java.net.SocketTimeoutException: The operation timed out".
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
如果你想給任何存在的HTTPClient(如DefaultHttpClient 或AndroidHttpClient)設置參數,你可以使用 setParams()方法。
httpClient.setParams(httpParameters);