1

在我的 Web 应用程序中,我有一个全局静态 HttpClient 用于应用程序的许多部分。它是这样创建的:

MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
params.setConnectionTimeout( 15000 );
params.setSoTimeout( 15000 );
connectionManager.setParams(params);
httpclient = new HttpClient(connectionManager);
HttpClientParams clientParams = new HttpClientParams();
clientParams.setParameter("http.protocol.allow-circular-redirects", true);
clientParams.setParameter("http.protocol.max-redirects", 4);
httpclient.setParams(clientParams);

对于大多数用例来说,超时都很好,但在特定的调用中,我想要更短的超时。所以我有:

GetMethod get = new GetMethod(finalUrl);

get.getParams().setParameter("http.socket.timeout", new Integer(1000));
get.getParams().setParameter("http.connection.timeout", new Integer(1000));
HttpClientUtil.getShortTimeoutInstance().executeMethod(get);

这没用。连接超时仍然是15000。我可以在GetMethod中设置特定的连接超时而不创建新的HttpClient实例(这是因为我认为创建一个新的HttpClient实例不是一个好主意)。

4

1 回答 1

0

你可能想看看

./impl/conn/tsccm/ThreadSafeClientConnManager.java

方法

ClientConnectionRequest requestConnection(final HttpRoute route, 
                                          final Object state)

为路由初始化连接池后,将继续使用最初配置的套接字 timeOut 值,除非您扩展/覆盖它。

public ClientConnectionRequest requestConnection(
        final HttpRoute route,
        final Object state) {

    final PoolEntryRequest poolRequest = pool.requestPoolEntry(
            route, state);

    return new ClientConnectionRequest() {

        public void abortRequest() {
            poolRequest.abortRequest();
        }

        public ManagedClientConnection getConnection(
                long timeout, TimeUnit tunit) throws InterruptedException,
                ConnectionPoolTimeoutException {
            if (route == null) {
                throw new IllegalArgumentException("Route may not be null.");
            }

            if (log.isDebugEnabled()) {
                log.debug("Get connection: " + route + ", timeout = " + timeout);
            }

            BasicPoolEntry entry = poolRequest.getPoolEntry(timeout, tunit);
            return new BasicPooledConnAdapter(ThreadSafeClientConnManager.this, entry);
        }

    };

}
于 2012-04-14T15:55:43.690 回答