HttpClient 如何在单个 GetMethod 中设置连接超时



在我的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。我可以在不创建新的 HttpClient 实例的情况下在 GetMethod 中设置特定的连接超时吗(这是因为我认为创建新的 HttpClient 实例不是一个好主意)。

你可能想看看

./impl/conn/tsccm/ThreadSafeClientConnManager.java

方法

ClientConnectionRequest requestConnection(final HttpRoute route, 
                                          final Object state)

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

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);
        }
    };
}

相关内容

  • 没有找到相关文章

最新更新