Apache Commons HttpClientでのタイムアウト
Apache Commons HttpClientでのタイムアウトの指定方法です。
HttpClient#setConnectionTimeout
がDeprecatedなので、調べてみました。
やり方がちょっとめんどくさいので、書いておきます。
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
params.setConnectionTimeout(3000); // タイムアウトmsec
HttpConnectionManager manager = new SimpleHttpConnectionManager();
manager.setParams(params);
HttpClient client = new HttpClient(manager);
GetMethod method = new GetMethod(url);
client.executeMethod(method);
なお、タイムアウトすると以下のExceptionをThrowしてくれます。
org.apache.commons.httpclient.ConnectTimeoutException: The host did not accept the connection within timeout of 3000 ms
HttpClientに設定できるパラメータにはHttpConnectionManagerParams以外にもHttpClientParamsというものがあります。
こちらにもHttpClientParams#setConnectionManagerTimeoutというメソッドがありますが、これではだめです。
HttpClientParams params = new HttpClientParams();
params.setConnectionManagerTimeout(3000);
HttpClient client = new HttpClient();
client.setParams(params);
はタイムアウトしません。
Posted in Java |
