接続ステータスを確認するための次の関数を作成しました。
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);
待ち時間が長くなりすぎないようにタイムアウトを設定する方法を知っている人はいますか?
ありがとう!
ベストアンサー1
私の例では、2 つのタイムアウトが設定されています。接続タイムアウトはスローされjava.net.SocketTimeoutException: Socket is not connected
、ソケット タイムアウトは ですjava.net.SocketTimeoutException: The operation timed out
。
HttpGet httpGet = new HttpGet(url);
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);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
既存の HTTPClient (DefaultHttpClient や AndroidHttpClient など) のパラメータを設定する場合は、関数setParams()を使用できます。
httpClient.setParams(httpParameters);